From 4bce6f5d72a27bccdd060165f63022e905efa3da Mon Sep 17 00:00:00 2001 From: Chen Date: Thu, 4 Dec 2025 10:57:50 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=20=E7=B4=A0=E6=9D=90?= =?UTF-8?q?=E5=BA=93=E6=96=B0=E5=A2=9E=E5=A4=84=E7=90=86=E4=BC=98=E5=8C=96?= =?UTF-8?q?=EF=BC=8C=E6=8F=90=E9=80=9F=EF=BC=8C=E5=85=B6=E4=BD=99bug?= =?UTF-8?q?=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 11 +- backend/database/db.js | 37 +- backend/database/dbPool.js | 77 ++-- backend/package.json | 4 +- backend/server.js | 115 +++-- backend/src/routes/image.js | 26 +- backend/src/routes/scan.js | 37 +- backend/src/services/LibraryService.js | 47 +- backend/src/services/ScanService.js | 139 ++---- backend/utils/cleanupManager.js | 57 +-- backend/utils/memoryMonitor.js | 39 +- backend/utils/scanManager.js | 201 ++++----- backend/utils/scanner.js | 196 ++++----- backend/utils/thumbnail.js | 22 - flypic/app/server/database/db.js | 38 +- flypic/app/server/database/dbPool.js | 96 +++-- flypic/app/server/package-lock.json | 249 +++++++---- flypic/app/server/package.json | 4 +- .../server/public/assets/index-CGwCzICz.js | 224 ---------- .../server/public/assets/index-CcwAM3eE.css | 1 + .../server/public/assets/index-DWWYNoqs.js | 226 ++++++++++ .../server/public/assets/index-lXh_CTLb.css | 1 - .../public/assets/layoutWorker-D6X91dDa.js | 1 - flypic/app/server/public/index.html | 4 +- flypic/app/server/routes/image.js | 297 ------------- flypic/app/server/routes/library.js | 238 ----------- flypic/app/server/routes/scan.js | 283 ------------ flypic/app/server/routes/watch.js | 81 ---- flypic/app/server/server.js | 349 ++++++++------- flypic/app/server/src/app.js | 95 +++++ flypic/app/server/src/config/constants.js | 62 +++ flypic/app/server/src/config/index.js | 42 ++ .../app/server/src/middleware/errorHandler.js | 97 +++++ flypic/app/server/src/middleware/validator.js | 67 +++ flypic/app/server/src/models/BaseModel.js | 44 ++ flypic/app/server/src/models/FolderModel.js | 115 +++++ flypic/app/server/src/models/ImageModel.js | 222 ++++++++++ flypic/app/server/src/routes/image.js | 170 ++++++++ flypic/app/server/src/routes/library.js | 109 +++++ flypic/app/server/src/routes/scan.js | 82 ++++ .../app/server/src/services/ImageService.js | 181 ++++++++ .../app/server/src/services/LibraryService.js | 275 ++++++++++++ flypic/app/server/src/services/ScanService.js | 178 ++++++++ flypic/app/server/src/utils/fieldMapper.js | 71 ++++ flypic/app/server/src/utils/logger.js | 31 ++ flypic/app/server/utils/cleanupManager.js | 233 ++++++++++ flypic/app/server/utils/fileWatcher.js | 242 ----------- flypic/app/server/utils/fileWatcherWorker.js | 64 --- flypic/app/server/utils/lightweightWatcher.js | 402 ++++++++++++++++++ flypic/app/server/utils/memoryDiagnostics.js | 176 ++++++++ flypic/app/server/utils/memoryMonitor.js | 195 +++++++++ flypic/app/server/utils/memoryStats.js | 63 +++ flypic/app/server/utils/migrateThumbnails.js | 148 +++++++ flypic/app/server/utils/scanManager.js | 201 ++++----- flypic/app/server/utils/scanner.js | 223 +++++----- flypic/app/server/utils/thumbnail.js | 66 ++- frontend/src/App.jsx | 96 ++--- frontend/src/api/endpoints/scan.js | 28 +- frontend/src/components/MainContent.jsx | 85 +--- frontend/src/components/Sidebar.jsx | 89 ++-- frontend/src/stores/useScanStore.js | 23 +- frontend/src/utils/imageCache.js | 5 +- scripts/build-fpk-docker.js | 172 -------- scripts/build-fpk.js | 136 ------ scripts/build.js | 188 ++++++++ scripts/test-in-docker.js | 55 --- 飞牛打包部署指南.md | 141 ++++-- 67 files changed, 4861 insertions(+), 3111 deletions(-) delete mode 100644 flypic/app/server/public/assets/index-CGwCzICz.js create mode 100644 flypic/app/server/public/assets/index-CcwAM3eE.css create mode 100644 flypic/app/server/public/assets/index-DWWYNoqs.js delete mode 100644 flypic/app/server/public/assets/index-lXh_CTLb.css delete mode 100644 flypic/app/server/public/assets/layoutWorker-D6X91dDa.js delete mode 100644 flypic/app/server/routes/image.js delete mode 100644 flypic/app/server/routes/library.js delete mode 100644 flypic/app/server/routes/scan.js delete mode 100644 flypic/app/server/routes/watch.js create mode 100644 flypic/app/server/src/app.js create mode 100644 flypic/app/server/src/config/constants.js create mode 100644 flypic/app/server/src/config/index.js create mode 100644 flypic/app/server/src/middleware/errorHandler.js create mode 100644 flypic/app/server/src/middleware/validator.js create mode 100644 flypic/app/server/src/models/BaseModel.js create mode 100644 flypic/app/server/src/models/FolderModel.js create mode 100644 flypic/app/server/src/models/ImageModel.js create mode 100644 flypic/app/server/src/routes/image.js create mode 100644 flypic/app/server/src/routes/library.js create mode 100644 flypic/app/server/src/routes/scan.js create mode 100644 flypic/app/server/src/services/ImageService.js create mode 100644 flypic/app/server/src/services/LibraryService.js create mode 100644 flypic/app/server/src/services/ScanService.js create mode 100644 flypic/app/server/src/utils/fieldMapper.js create mode 100644 flypic/app/server/src/utils/logger.js create mode 100644 flypic/app/server/utils/cleanupManager.js delete mode 100644 flypic/app/server/utils/fileWatcher.js delete mode 100644 flypic/app/server/utils/fileWatcherWorker.js create mode 100644 flypic/app/server/utils/lightweightWatcher.js create mode 100644 flypic/app/server/utils/memoryDiagnostics.js create mode 100644 flypic/app/server/utils/memoryMonitor.js create mode 100644 flypic/app/server/utils/memoryStats.js create mode 100644 flypic/app/server/utils/migrateThumbnails.js delete mode 100644 scripts/build-fpk-docker.js delete mode 100644 scripts/build-fpk.js create mode 100644 scripts/build.js delete mode 100644 scripts/test-in-docker.js diff --git a/README.md b/README.md index 43ef78e..ee5a176 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # FlyPic 飞图 -专为飞牛 fnOS 设计的轻量、快速、稳定的图像素材检索浏览应用。 +主要飞牛 fnOS 设计的轻量、快速、稳定的图像素材检索浏览应用。 ## ✨ 核心特性 @@ -8,18 +8,19 @@ - 🛡️ **非侵入式** - 只在素材库目录创建 .flypic 文件夹存储索引和缩略图,不修改任何原始文件 - 🔄 **实时同步** - 基于 Worker Thread 的文件监控,自动检测新增、删除、修改 - 🌐 **远程访问** - 支持 FN Connect 远程访问,随时随地浏览管理图片素材库 -- 🎨 **现代界面** - Google Photos 风格瀑布流布局,支持亮色/暗色主题,响应式设计 +- 🎨 **现代界面** - 固定行高瀑布流布局,支持亮色/暗色主题,响应式设计 - 🔍 **智能搜索** - 多关键词组合搜索,高级筛选(格式/大小/方向) - 📱 **移动适配** - 响应式设计,手机上也能流畅使用 - 🆓 **开源免费** - 100% 开源,MIT 协议 +- 其他平台 ## 🛠️ 技术栈 -**前端**:React 18 + Vite 5 + TailwindCSS + Zustand + react-window + react-photo-view + Lucide Icons +**前端**:React 18 + Vite 5 + TailwindCSS + Zustand + react-window + react-photo-view -**后端**:Node.js + Express + Sharp + better-sqlite3 + Socket.IO + chokidar +**后端**:Node.js + Express + Sharp + better-sqlite3 + Socket.IO -**架构**:三层架构(Config → Model → Service → Route)+ 模块化前端(Store → API → Components) +**架构**:三层架构(Config → Model → Service → Route)+ 模块化前端(Store → Hooks → API) ## 🚀 快速开始 diff --git a/backend/database/db.js b/backend/database/db.js index 934fde1..5ed1457 100644 --- a/backend/database/db.js +++ b/backend/database/db.js @@ -19,19 +19,23 @@ class LibraryDatabase { this.db = new Database(this.dbPath); - // 超激进内存优化配置 - // 使用 DELETE 模式而非 WAL(WAL 可能导致内存泄漏) - this.db.pragma('journal_mode = DELETE'); // 使用 DELETE 模式(更低内存) + // 优化数据库性能 + this.db.pragma('journal_mode = WAL'); // 启用 WAL 模式,支持并发读写 this.db.pragma('synchronous = NORMAL'); // 平衡性能和安全性 - this.db.pragma('cache_size = -4096'); // 4MB 缓存(超激进:从8MB降至4MB) - this.db.pragma('temp_store = FILE'); // 临时表存储在磁盘 - this.db.pragma('mmap_size = 0'); // 禁用内存映射 - this.db.pragma('page_size = 4096'); // 4KB 页面大小(减少内存占用) - - console.log('[LibraryDatabase] Ultra-aggressive memory optimization applied:'); - console.log(' cache_size: 4MB, temp_store: FILE, mmap_size: 0, page_size: 4KB'); + this.db.pragma('cache_size = -64000'); // 64MB 缓存 + this.db.pragma('temp_store = MEMORY'); // 临时表存储在内存 + this.db.pragma('mmap_size = 268435456'); // 256MB 内存映射 this.initTables(); + + // 启动 WAL 定期 checkpoint(每 5 分钟) + this.walCheckpointInterval = setInterval(() => { + try { + this.db.pragma('wal_checkpoint(PASSIVE)'); + } catch (e) { + console.warn('[DB] WAL checkpoint warning:', e.message); + } + }, 300000); // 5 分钟 } initTables() { @@ -400,6 +404,19 @@ class LibraryDatabase { } close() { + // 清理 WAL checkpoint 定时器 + if (this.walCheckpointInterval) { + clearInterval(this.walCheckpointInterval); + this.walCheckpointInterval = null; + } + + // 执行最后一次 checkpoint + try { + this.db.pragma('wal_checkpoint(TRUNCATE)'); + } catch (e) { + console.warn('[DB] Final WAL checkpoint warning:', e.message); + } + this.db.close(); } } diff --git a/backend/database/dbPool.js b/backend/database/dbPool.js index 07332f7..3749f62 100644 --- a/backend/database/dbPool.js +++ b/backend/database/dbPool.js @@ -6,9 +6,14 @@ const LibraryDatabase = require('./db'); */ class DatabasePool { constructor() { + // 单例模式:确保只有一个实例,避免多个定时器 + if (DatabasePool.instance) { + return DatabasePool.instance; + } + DatabasePool.instance = this; + this.connections = new Map(); // libraryPath -> { db, lastUsed, refCount } - this.maxConnections = 1; // 最大连接数:1 - this.maxIdleTime = 60000; // 60秒未使用则关闭(保持连接复用,减少创建/关闭) + this.maxIdleTime = 60000; // 60秒未使用则关闭 this.cleanupInterval = null; // 启动定期清理 @@ -23,16 +28,6 @@ class DatabasePool { let conn = this.connections.get(libraryPath); if (!conn) { - // 强制执行最大连接数限制:如果已有连接,先关闭所有空闲连接 - if (this.connections.size >= this.maxConnections) { - for (const [path, existingConn] of this.connections.entries()) { - if (existingConn.refCount === 0) { - console.log(`[DBPool] Max connections reached, closing idle: ${path}`); - this.close(path); - } - } - } - // 创建新连接 const db = new LibraryDatabase(libraryPath); conn = { @@ -41,7 +36,6 @@ class DatabasePool { refCount: 0 }; this.connections.set(libraryPath, conn); - console.log(`[DBPool] Created new connection for: ${libraryPath} (total: ${this.connections.size}/${this.maxConnections})`); } // 更新使用时间和引用计数 @@ -72,17 +66,19 @@ class DatabasePool { // 强制设置引用计数为0 conn.refCount = 0; - // 关闭数据库连接 + // 执行 checkpoint 确保 WAL 写入主数据库 if (conn.db && conn.db.db) { - // 注意:db.js 使用 DELETE 模式而非 WAL,无需 checkpoint - // 直接关闭连接即可 - conn.db.close(); + try { + conn.db.db.pragma('wal_checkpoint(TRUNCATE)'); + } catch (e) { + console.warn(`[DBPool] WAL checkpoint warning:`, e.message); + } } + conn.db.close(); this.connections.delete(libraryPath); - console.log(`[DBPool] Closed connection for: ${libraryPath}`); } catch (error) { - console.error(`[DBPool] Error closing connection:`, error); + console.error(`❌ 关闭数据库连接失败:`, error.message); // 即使出错也删除引用 this.connections.delete(libraryPath); } @@ -93,27 +89,28 @@ class DatabasePool { * 关闭所有连接 */ closeAll() { - console.log(`[DBPool] Closing all connections (${this.connections.size} total)`); - - for (const [path, conn] of this.connections.entries()) { - try { - // 强制设置引用计数为0 - conn.refCount = 0; - - // 注意:db.js 使用 DELETE 模式而非 WAL,无需 checkpoint - // 直接关闭连接即可 - conn.db.close(); - console.log(`[DBPool] Closed connection for: ${path}`); - } catch (error) { - console.error(`[DBPool] Error closing connection for ${path}:`, error); - } - } - this.connections.clear(); - + // 先清理定时器,避免在关闭过程中触发清理 if (this.cleanupInterval) { clearInterval(this.cleanupInterval); this.cleanupInterval = null; } + + for (const [path, conn] of this.connections.entries()) { + try { + // 执行 checkpoint 确保 WAL 写入主数据库 + if (conn.db && conn.db.db) { + try { + conn.db.db.pragma('wal_checkpoint(TRUNCATE)'); + } catch (e) { + console.warn(`[DBPool] WAL checkpoint warning:`, e.message); + } + } + conn.db.close(); + } catch (error) { + console.error(`❌ 关闭数据库连接失败:`, error.message); + } + } + this.connections.clear(); } /** @@ -121,7 +118,6 @@ class DatabasePool { * 与 closeAll() 相同,但提供明确的语义 */ forceCloseAll() { - console.log('[DBPool] Force closing all connections (emergency cleanup)'); this.closeAll(); } @@ -144,14 +140,11 @@ class DatabasePool { toClose.forEach(path => this.close(path)); if (toClose.length > 0) { - console.log(`[DBPool] Cleaned up ${toClose.length} idle connections`); - // 关闭连接后立即强制 GC if (global.gc) { for (let i = 0; i < 3; i++) { global.gc(); } - console.log(`[DBPool] Forced GC after closing connections`); } } }, 10000); // 每10秒检查一次(更频繁) @@ -191,10 +184,6 @@ class DatabasePool { } toClose.forEach(path => this.close(path)); - - if (toClose.length > 0) { - console.log(`[DBPool] Cleared ${toClose.length} idle connections`); - } } } diff --git a/backend/package.json b/backend/package.json index 76751a2..9956ce7 100644 --- a/backend/package.json +++ b/backend/package.json @@ -4,8 +4,8 @@ "description": "FlyPic backend server", "main": "server.js", "scripts": { - "dev": "cross-env PORT=15002 nodemon server.js", - "start": "node server.js" + "dev": "cross-env PORT=15002 nodemon --expose-gc server.js", + "start": "node --expose-gc server.js" }, "dependencies": { "better-sqlite3": "^9.2.2", diff --git a/backend/server.js b/backend/server.js index 51dd4a8..8e6e1cd 100644 --- a/backend/server.js +++ b/backend/server.js @@ -35,13 +35,13 @@ if (!FRONTEND_DIST) { for (const p of possiblePaths) { if (fs.existsSync(p)) { FRONTEND_DIST = p; - console.log('✅ Found frontend at:', p); + console.log('✅ 前端目录:', p); break; } } if (!FRONTEND_DIST) { - console.log('⚠️ Frontend not found, API-only mode'); + console.log('⚠️ 未找到前端,API模式'); } } @@ -89,15 +89,18 @@ server.on('request', app); // Socket.IO 连接处理 io.on('connection', (socket) => { - console.log('✅ Socket.IO client connected:', socket.id); + console.log('✅ 客户端连接:', socket.id); socket.on('disconnect', () => { - console.log('❌ Socket.IO client disconnected:', socket.id); + console.log('❌ 客户端断开:', socket.id); }); }); -// 启动内存监控 -const memoryMonitor = new MemoryMonitor(); +// 启动内存监控(开发模式:每30秒输出RSS) +const memoryMonitor = new MemoryMonitor({ + devMode: true, + devLogInterval: 30000 // 30秒 +}); memoryMonitor.start(); // 启动清理管理器 @@ -106,36 +109,95 @@ cleanupManager.startRoutineCleanup(); // 启动服务器 server.listen(PORT, () => { - console.log('\n🚀 FlyPic Server (New Architecture) Started'); - console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'); - console.log(`📡 Server running on http://localhost:${PORT}`); - console.log(`🔌 Socket.IO ready`); - console.log(`📁 Frontend: ${FRONTEND_DIST || 'Not found (API-only mode)'}`); - console.log(`🏗️ Architecture: Config → Model → Service → Route`); - console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n'); - - // 为当前素材库启动文件监控 + console.log('\n🚀 FlyPic 服务器已启动'); + console.log(`📡 端口: ${PORT}`); + console.log(`🔌 Socket.IO 就绪`); + if (FRONTEND_DIST) console.log(`📁 前端: ${FRONTEND_DIST}`); + console.log(''); + try { const currentConfig = config.loadConfig(); + + // 恢复所有素材库的扫描状态 + if (currentConfig.libraries && currentConfig.libraries.length > 0) { + scanManager.restoreAllStates(currentConfig.libraries); + + // 检查是否有未完成的扫描,自动继续 + const activeStates = scanManager.getAllActiveStates(); + if (Object.keys(activeStates).length > 0) { + console.log(`📊 发现 ${Object.keys(activeStates).length} 个活跃扫描`); + } + + for (const [libraryId, state] of Object.entries(activeStates)) { + const lib = currentConfig.libraries.find(l => l.id === libraryId); + if (lib && state.status === 'scanning') { + console.log(`🔄 恢复扫描: ${lib.name} (${state.progress?.percent || 0}%)`); + + // 立即恢复扫描状态(让前端能检测到) + scanManager.scanStates.set(libraryId, { + status: 'scanning', + progress: state.progress || { current: 0, total: 0, percent: 0 }, + startTime: state.startTime || Date.now() + }); + + // 立即向所有连接的客户端推送扫描状态 + io.emit('scanProgress', { + libraryId, + ...state.progress, + resuming: true + }); + + // 延迟启动实际扫描,等服务完全准备好 + setTimeout(() => { + const db = dbPool.acquire(lib.path); + // 继续扫描(从中断处继续) + scanner.scanLibrary( + lib.path, + db, + (progress) => { + io.emit('scanProgress', { libraryId, ...progress }); + }, + libraryId + ).then(() => { + scanManager.completeScan(libraryId); + io.emit('scanComplete', { libraryId }); + dbPool.release(lib.path); + console.log(`✅ 扫描完成: ${lib.name}`); + }).catch((err) => { + console.error(`❌ 扫描失败: ${lib.name}`, err.message); + scanManager.completeScan(libraryId); + dbPool.release(lib.path); + }); + }, 2000); + } + } + } + + // 为当前素材库启动文件监控 if (currentConfig.currentLibraryId) { const currentLib = currentConfig.libraries.find(lib => lib.id === currentConfig.currentLibraryId); if (currentLib) { lightweightWatcher.watch(currentLib.id, currentLib.path, currentLib.name, io); - console.log(`📂 File watcher started for: ${currentLib.name}`); } } } catch (e) { - console.warn('⚠️ Failed to start file watcher:', e.message); + console.warn('⚠️ 初始化失败:', e.message); } }); +// 标记是否正在关闭 +let isShuttingDown = false; + // 优雅关闭 const shutdown = async () => { - console.log('\n🛑 Shutting down gracefully...'); + if (isShuttingDown) return; + isShuttingDown = true; + + console.log('\n🛑 正在关闭服务器...'); // 停止接受新连接 server.close(() => { - console.log('✅ HTTP server closed'); + console.log('✅ HTTP 服务器已关闭'); }); // 停止监控 @@ -145,27 +207,30 @@ const shutdown = async () => { // 停止所有文件监控 lightweightWatcher.stopAll(); + // 等待扫描任务完成当前批次(最多等2秒) + await new Promise(resolve => setTimeout(resolve, 2000)); + // 关闭所有数据库连接 dbPool.closeAll(); - // 等待资源释放 - await new Promise(resolve => setTimeout(resolve, 1000)); - - console.log('✅ Shutdown complete'); + console.log('✅ 关闭完成'); process.exit(0); }; +// 导出关闭状态供其他模块检查 +module.exports.isShuttingDown = () => isShuttingDown; + process.on('SIGTERM', shutdown); process.on('SIGINT', shutdown); // 错误处理 process.on('uncaughtException', (error) => { - console.error('💥 Uncaught Exception:', error); + console.error('💥 未捕获异常:', error.message); shutdown(); }); process.on('unhandledRejection', (reason, promise) => { - console.error('💥 Unhandled Rejection at:', promise, 'reason:', reason); + console.error('💥 未处理的Promise拒绝:', reason); shutdown(); }); diff --git a/backend/src/routes/image.js b/backend/src/routes/image.js index cdc674e..418f56e 100644 --- a/backend/src/routes/image.js +++ b/backend/src/routes/image.js @@ -103,52 +103,32 @@ router.get('/:id', asyncHandler(async (req, res) => { router.get('/thumbnail/:libraryId/:filename', (req, res) => { const { libraryId, filename } = req.params; - console.log(`[Thumbnail] ========== NEW REQUEST ==========`); - console.log(`[Thumbnail] LibraryId: ${libraryId}, Filename: ${filename}`); - try { const config = require('../../utils/config').loadConfig(); - console.log(`[Thumbnail] All libraries:`, config.libraries.map(l => ({ id: l.id, type: typeof l.id }))); // 尝试两种方式查找:数字和字符串 let library = config.libraries.find(lib => lib.id === parseInt(libraryId)); if (!library) { - library = config.libraries.find(lib => lib.id == libraryId); // 使用 == 宽松比较 + library = config.libraries.find(lib => lib.id == libraryId); } if (!library) { - console.log(`[Thumbnail] Library not found: ${libraryId} (type: ${typeof libraryId})`); return res.status(404).send('Library not found'); } - console.log(`[Thumbnail] Library path: ${library.path}`); - // 使用分片结构:取文件名前2个字符作为分片目录 - const hash = filename.replace(/\.[^/.]+$/, ''); // 移除扩展名 + const hash = filename.replace(/\.[^/.]+$/, ''); const shard = hash.slice(0, 2); const flypicPath = getFlypicPath(library.path); const thumbnailPath = path.join(flypicPath, 'thumbnails', shard, filename); - console.log(`[Thumbnail] Hash: ${hash}, Shard: ${shard}`); - console.log(`[Thumbnail] Full path: ${thumbnailPath}`); - console.log(`[Thumbnail] File exists: ${fs.existsSync(thumbnailPath)}`); - if (!fs.existsSync(thumbnailPath)) { - // 列出分片目录的内容 - const shardDir = path.join(flypicPath, 'thumbnails', shard); - if (fs.existsSync(shardDir)) { - const files = fs.readdirSync(shardDir); - console.log(`[Thumbnail] Files in shard dir (${shard}):`, files.slice(0, 5)); - } else { - console.log(`[Thumbnail] Shard directory does not exist: ${shardDir}`); - } return res.status(404).send('Thumbnail not found'); } - console.log(`[Thumbnail] ✅ Serving file`); res.sendFile(thumbnailPath); } catch (error) { - console.error('[Thumbnail] Error:', error); + console.error('❌ 缩略图错误:', error.message); res.status(500).send('Error serving thumbnail'); } }); diff --git a/backend/src/routes/scan.js b/backend/src/routes/scan.js index da5415c..a017668 100644 --- a/backend/src/routes/scan.js +++ b/backend/src/routes/scan.js @@ -46,34 +46,6 @@ router.post('/sync', }) ); -/** - * 停止扫描 - * POST /api/scan/stop - * Body: { libraryId } - */ -router.post('/stop', - validateRequired(['libraryId']), - asyncHandler(async (req, res) => { - const { libraryId } = req.body; - const result = scanService.stopScan(libraryId); - res.json({ success: true, data: result }); - }) -); - -/** - * 继续扫描 - * POST /api/scan/resume - * Body: { libraryId } - */ -router.post('/resume', - validateRequired(['libraryId']), - asyncHandler(async (req, res) => { - const { libraryId } = req.body; - const result = scanService.resumeScan(libraryId); - res.json({ success: true, data: result }); - }) -); - /** * 获取扫描状态 * GET /api/scan/status/:libraryId @@ -84,6 +56,15 @@ router.get('/status/:libraryId', asyncHandler(async (req, res) => { res.json({ success: true, data: result }); })); +/** + * 获取所有活跃的扫描状态 + * GET /api/scan/active-states + */ +router.get('/active-states', asyncHandler(async (req, res) => { + const result = scanService.getAllActiveStates(); + res.json({ success: true, data: result }); +})); + /** * 修复文件夹路径 * POST /api/scan/fix-folders diff --git a/backend/src/services/LibraryService.js b/backend/src/services/LibraryService.js index 3081cb1..06097f2 100644 --- a/backend/src/services/LibraryService.js +++ b/backend/src/services/LibraryService.js @@ -39,23 +39,60 @@ class LibraryService { throw new ValidationError('Name and path are required'); } - if (!fs.existsSync(libraryPath)) { + // 规范化路径 + const normalizedPath = path.normalize(libraryPath); + console.log(`[LibraryService] Creating library: name=${name}, path=${normalizedPath}`); + + if (!fs.existsSync(normalizedPath)) { + console.log(`[LibraryService] Path does not exist: ${normalizedPath}`); throw new ValidationError('Path does not exist', 'path'); } + // 检查文件夹访问权限 + try { + // 尝试读取目录 + fs.readdirSync(normalizedPath); + + // 尝试在目录中创建测试文件(检查写权限) + const testFile = path.join(normalizedPath, '.flypic-test'); + try { + fs.writeFileSync(testFile, 'test'); + fs.unlinkSync(testFile); + } catch (writeError) { + console.log(`[LibraryService] No write permission: ${normalizedPath}`); + throw new ValidationError( + '无法访问该文件夹。请在飞牛 fnOS 的"数据共享"中将此文件夹添加到 FlyPic 应用的访问权限。', + 'permission' + ); + } + } catch (readError) { + if (readError.code === 'EACCES' || readError.code === 'EPERM') { + console.log(`[LibraryService] No access permission: ${normalizedPath}`); + throw new ValidationError( + '无法访问该文件夹。请在飞牛 fnOS 的"数据共享"中将此文件夹添加到 FlyPic 应用的访问权限。', + 'permission' + ); + } + // 如果不是权限错误,继续抛出 + if (readError.name !== 'ValidationError') { + throw readError; + } + throw readError; + } + // 检查路径是否已存在 const config = this.configManager.load(); - const existingLib = config.libraries.find(lib => lib.path === libraryPath); + const existingLib = config.libraries.find(lib => lib.path === normalizedPath); if (existingLib) { throw new ValidationError('Library path already exists', 'path'); } // 创建素材库 - const id = this.configManager.addLibrary(name, libraryPath); + const id = this.configManager.addLibrary(name, normalizedPath); // 检查是否有现有索引 - const flypicDir = getFlypicPath(libraryPath); - const dbPath = getDatabasePath(libraryPath); + const flypicDir = getFlypicPath(normalizedPath); + const dbPath = getDatabasePath(normalizedPath); const hasExistingIndex = fs.existsSync(flypicDir) && fs.existsSync(dbPath); return { diff --git a/backend/src/services/ScanService.js b/backend/src/services/ScanService.js index f7ca545..519b0e0 100644 --- a/backend/src/services/ScanService.js +++ b/backend/src/services/ScanService.js @@ -1,6 +1,6 @@ /** - * 扫描服务层 - * 封装扫描相关的业务逻辑 + * 扫描服务层(简化版) + * 无暂停功能,只负责扫描和进度推送 */ const { NotFoundError, ValidationError } = require('../middleware/errorHandler'); @@ -22,35 +22,21 @@ class ScanService { const db = this.dbPool.acquire(library.path); try { - // 检查是否已在扫描 if (this.scanManager.isScanning(libraryId)) { throw new ValidationError('Scan already in progress', 'libraryId'); } - // 开始扫描 if (wait) { - // 同步模式:等待扫描完成 await this.scanner.scanLibrary( library.path, db, - (progress) => this._emitProgress(libraryId, progress) - ); - - return { - success: true, - message: 'Scan completed', + (progress) => this._emitProgress(libraryId, progress), libraryId - }; + ); + return { success: true, message: 'Scan completed', libraryId }; } else { - // 异步模式:后台扫描 this._startAsyncScan(libraryId, library.path, db); - - return { - success: true, - message: 'Scan started', - libraryId, - async: true - }; + return { success: true, message: 'Scan started', libraryId, async: true }; } } catch (error) { this.dbPool.release(library.path); @@ -66,35 +52,21 @@ class ScanService { const db = this.dbPool.acquire(library.path); try { - // 检查是否已在扫描 if (this.scanManager.isScanning(libraryId)) { throw new ValidationError('Scan already in progress', 'libraryId'); } - // 开始增量同步 if (wait) { - // 同步模式 - await this.scanner.incrementalSync( + await this.scanner.syncLibrary( library.path, db, + false, (progress) => this._emitProgress(libraryId, progress) ); - - return { - success: true, - message: 'Sync completed', - libraryId - }; + return { success: true, message: 'Sync completed', libraryId }; } else { - // 异步模式 this._startAsyncSync(libraryId, library.path, db); - - return { - success: true, - message: 'Sync started', - libraryId, - async: true - }; + return { success: true, message: 'Sync started', libraryId, async: true }; } } catch (error) { this.dbPool.release(library.path); @@ -102,44 +74,6 @@ class ScanService { } } - /** - * 停止扫描 - */ - stopScan(libraryId) { - const library = this._getLibrary(libraryId); - - if (!this.scanManager.isScanning(libraryId)) { - throw new ValidationError('No scan in progress', 'libraryId'); - } - - this.scanManager.pauseScan(libraryId); - - return { - success: true, - message: 'Scan stopped', - libraryId - }; - } - - /** - * 继续扫描 - */ - resumeScan(libraryId) { - const library = this._getLibrary(libraryId); - - if (!this.scanManager.isPaused(libraryId)) { - throw new ValidationError('No paused scan found', 'libraryId'); - } - - this.scanManager.resumeScan(libraryId); - - return { - success: true, - message: 'Scan resumed', - libraryId - }; - } - /** * 获取扫描状态 */ @@ -149,13 +83,19 @@ class ScanService { return { libraryId, - isScanning: this.scanManager.isScanning(libraryId), - isPaused: this.scanManager.isPaused(libraryId), + status: state?.status || 'idle', progress: state?.progress || null, startTime: state?.startTime || null }; } + /** + * 获取所有活跃状态 + */ + getAllActiveStates() { + return this.scanManager.getAllActiveStates(); + } + /** * 修复文件夹路径 */ @@ -165,12 +105,7 @@ class ScanService { try { await this.scanner.fixFolderPaths(library.path, db); - - return { - success: true, - message: 'Folders fixed', - libraryId - }; + return { success: true, message: 'Folders fixed', libraryId }; } finally { this.dbPool.release(library.path); } @@ -178,13 +113,13 @@ class ScanService { /** * 启动异步扫描 - * @private */ _startAsyncScan(libraryId, libraryPath, db) { this.scanner.scanLibrary( libraryPath, db, - (progress) => this._emitProgress(libraryId, progress) + (progress) => this._emitProgress(libraryId, progress), + libraryId ).then(() => { this._emitComplete(libraryId); this.dbPool.release(libraryPath); @@ -196,12 +131,12 @@ class ScanService { /** * 启动异步同步 - * @private */ _startAsyncSync(libraryId, libraryPath, db) { - this.scanner.incrementalSync( + this.scanner.syncLibrary( libraryPath, db, + false, (progress) => this._emitProgress(libraryId, progress) ).then(() => { this._emitComplete(libraryId); @@ -212,54 +147,30 @@ class ScanService { }); } - /** - * 发送进度更新 - * @private - */ _emitProgress(libraryId, progress) { if (this.io) { - this.io.emit('scanProgress', { - libraryId, - ...progress - }); + this.io.emit('scanProgress', { libraryId, ...progress }); } } - /** - * 发送完成事件 - * @private - */ _emitComplete(libraryId) { if (this.io) { this.io.emit('scanComplete', { libraryId }); } } - /** - * 发送错误事件 - * @private - */ _emitError(libraryId, error) { if (this.io) { - this.io.emit('scanError', { - libraryId, - error: error.message - }); + this.io.emit('scanError', { libraryId, error: error.message }); } } - /** - * 获取素材库对象 - * @private - */ _getLibrary(libraryId) { const config = this.configManager.load(); const library = config.libraries.find(lib => lib.id === libraryId); - if (!library) { throw new NotFoundError('Library', libraryId); } - return library; } } diff --git a/backend/utils/cleanupManager.js b/backend/utils/cleanupManager.js index 518f522..b89ad76 100644 --- a/backend/utils/cleanupManager.js +++ b/backend/utils/cleanupManager.js @@ -19,14 +19,9 @@ class CleanupManager { * Start routine cleanup */ startRoutineCleanup() { - if (this.isRunning) { - console.log('[CleanupManager] Routine cleanup already running'); - return; - } - - console.log('[CleanupManager] Starting routine cleanup'); - console.log(` Interval: ${this.routineInterval}ms`); + if (this.isRunning) return; + console.log('🧹 清理管理器已启动'); this.isRunning = true; this.routineIntervalId = setInterval(() => { @@ -38,11 +33,9 @@ class CleanupManager { * Stop routine cleanup */ stopRoutineCleanup() { - if (!this.isRunning) { - return; - } + if (!this.isRunning) return; - console.log('[CleanupManager] Stopping routine cleanup'); + console.log('🧹 清理管理器已停止'); if (this.routineIntervalId) { clearInterval(this.routineIntervalId); @@ -81,11 +74,10 @@ class CleanupManager { this.cleanupCount++; this.lastCleanupTime = Date.now(); - // 总是显示日志(帮助诊断) - console.log('[CleanupManager] Routine cleanup completed'); - console.log(` Caches cleared: ${cachesCleared}`); - console.log(` Heap reclaimed: ${(memoryReclaimed / 1024 / 1024).toFixed(2)} MB`); - console.log(` RSS: ${rssBefore.toFixed(0)}MB → ${rssAfter.toFixed(0)}MB (${rssReclaimed > 0 ? '-' : '+'}${Math.abs(rssReclaimed).toFixed(0)}MB)`); + // 只在内存回收显著时输出日志 + if (Math.abs(rssReclaimed) > 10) { + console.log(`🧹 内存清理: ${rssBefore.toFixed(0)}MB → ${rssAfter.toFixed(0)}MB`); + } return { memoryBefore, @@ -95,7 +87,7 @@ class CleanupManager { connectionsCleared: 0 }; } catch (error) { - console.error('[CleanupManager] Routine cleanup error:', error); + console.error('❌ 清理失败:', error.message); return null; } } @@ -107,7 +99,7 @@ class CleanupManager { * - Force garbage collection multiple times (3+) */ executeEmergencyCleanup() { - console.log('[CleanupManager] 🚨 Executing EMERGENCY cleanup...'); + console.log('🚨 执行紧急内存清理...'); const memoryBefore = this.getMemoryStats(); @@ -118,15 +110,15 @@ class CleanupManager { try { this.dbPool.closeAll(); connectionsCleared = 1; - console.log('[CleanupManager] ✓ Database connections closed'); + console.log(' ✓ 数据库连接已关闭'); } catch (error) { - console.error('[CleanupManager] ✗ Failed to close connections:', error.message); + console.error(' ✗ 关闭连接失败:', error.message); } } // 2. Clear all registered caches const cachesCleared = this.clearAllCaches(); - console.log(`[CleanupManager] ✓ ${cachesCleared} caches cleared`); + console.log(` ✓ 已清理 ${cachesCleared} 个缓存`); // 3. Force garbage collection multiple times (minimum 3) this.forceGarbageCollection(3); @@ -134,10 +126,7 @@ class CleanupManager { const memoryAfter = this.getMemoryStats(); const memoryReclaimed = memoryBefore.heapUsed - memoryAfter.heapUsed; - console.log('[CleanupManager] Emergency cleanup completed'); - console.log(` Memory before: ${(memoryBefore.heapUsed / 1024 / 1024).toFixed(2)} MB`); - console.log(` Memory after: ${(memoryAfter.heapUsed / 1024 / 1024).toFixed(2)} MB`); - console.log(` Memory reclaimed: ${(memoryReclaimed / 1024 / 1024).toFixed(2)} MB`); + console.log(`✅ 紧急清理完成: 回收 ${(memoryReclaimed / 1024 / 1024).toFixed(0)}MB`); return { memoryBefore, @@ -147,7 +136,7 @@ class CleanupManager { connectionsCleared }; } catch (error) { - console.error('[CleanupManager] Emergency cleanup error:', error); + console.error('❌ 紧急清理失败:', error.message); return null; } } @@ -157,23 +146,16 @@ class CleanupManager { * @param {number} iterations - Number of GC iterations (minimum 3) */ forceGarbageCollection(iterations = 3) { - if (!global.gc) { - console.warn('[CleanupManager] Garbage collection not available (run with --expose-gc)'); - return; - } + if (!global.gc) return; const actualIterations = Math.max(3, iterations); - console.log(`[CleanupManager] Running GC ${actualIterations} times...`); - for (let i = 0; i < actualIterations; i++) { try { global.gc(); } catch (error) { - console.error(`[CleanupManager] GC iteration ${i + 1} failed:`, error.message); + console.error(` ✗ GC失败 (${i + 1}/${actualIterations}):`, error.message); } } - - console.log('[CleanupManager] ✓ Garbage collection completed'); } /** @@ -190,7 +172,7 @@ class CleanupManager { cleared++; } } catch (error) { - console.error(`[CleanupManager] Failed to clear cache "${name}":`, error.message); + console.error(`❌ 清理缓存失败 "${name}":`, error.message); } } @@ -204,12 +186,11 @@ class CleanupManager { */ registerCache(name, cache) { if (!cache || typeof cache.clear !== 'function') { - console.warn(`[CleanupManager] Cache "${name}" does not have a clear() method`); + console.warn(`⚠️ 缓存 "${name}" 无clear()方法`); return; } this.caches.set(name, cache); - console.log(`[CleanupManager] Registered cache: ${name}`); } /** diff --git a/backend/utils/memoryMonitor.js b/backend/utils/memoryMonitor.js index f6740f5..1b89ec5 100644 --- a/backend/utils/memoryMonitor.js +++ b/backend/utils/memoryMonitor.js @@ -24,15 +24,9 @@ class MemoryMonitor { * Start monitoring memory usage */ start() { - if (this.isRunning) { - console.log('[MemoryMonitor] Already running'); - return; - } + if (this.isRunning) return; - console.log('[MemoryMonitor] Starting memory monitoring'); - console.log(` Warning threshold: ${(this.warningThreshold / 1024 / 1024).toFixed(0)}MB`); - console.log(` Danger threshold: ${(this.dangerThreshold / 1024 / 1024).toFixed(0)}MB`); - console.log(` Check interval: ${this.checkInterval}ms`); + console.log('📊 内存监控已启动'); this.isRunning = true; @@ -43,7 +37,6 @@ class MemoryMonitor { // Start development mode logging if (this.devMode) { - console.log('[MemoryMonitor] Development mode: logging every 30 seconds'); this.devLogIntervalId = setInterval(() => { const stats = this.getMemoryStats(); this.logMemoryStats(stats, 'DEV'); @@ -58,11 +51,9 @@ class MemoryMonitor { * Stop monitoring */ stop() { - if (!this.isRunning) { - return; - } + if (!this.isRunning) return; - console.log('[MemoryMonitor] Stopping memory monitoring'); + console.log('📊 内存监控已停止'); if (this.intervalId) { clearInterval(this.intervalId); @@ -125,7 +116,7 @@ class MemoryMonitor { this.lastWarningTime = now; - console.warn('[MemoryMonitor] ⚠️ WARNING: Memory usage high'); + console.warn('⚠️ 内存使用偏高'); this.logMemoryStats(stats, 'WARNING'); } @@ -142,12 +133,12 @@ class MemoryMonitor { this.lastDangerTime = now; - console.error('[MemoryMonitor] 🚨 DANGER: Memory usage critical!'); + console.error('🚨 内存使用危险!'); this.logMemoryStats(stats, 'DANGER'); // Trigger emergency cleanup if cleanup manager is available if (this.cleanupManager) { - console.log('[MemoryMonitor] Triggering emergency cleanup...'); + console.log('🚨 触发紧急清理...'); try { this.cleanupManager.executeEmergencyCleanup(); @@ -155,11 +146,9 @@ class MemoryMonitor { setTimeout(() => { const afterStats = this.getMemoryStats(); const afterRSS = afterStats.rss / 1024 / 1024; - console.log(`[MemoryMonitor] After emergency cleanup: RSS = ${afterRSS.toFixed(0)}MB`); // 如果 RSS 仍然很高,强制更多 GC if (afterRSS > 500) { - console.log('[MemoryMonitor] RSS still high, forcing additional GC...'); if (global.gc) { for (let i = 0; i < 10; i++) { global.gc(); @@ -168,10 +157,8 @@ class MemoryMonitor { } }, 1000); } catch (error) { - console.error('[MemoryMonitor] Emergency cleanup failed:', error); + console.error('❌ 紧急清理失败:', error.message); } - } else { - console.warn('[MemoryMonitor] No cleanup manager available'); } } @@ -185,12 +172,10 @@ class MemoryMonitor { const externalMB = (stats.external / 1024 / 1024).toFixed(2); const arrayBuffersMB = (stats.arrayBuffers / 1024 / 1024).toFixed(2); - console.log(`[MemoryMonitor] ${level} - Memory Statistics:`); - console.log(` Heap Used: ${heapUsedMB} MB`); - console.log(` Heap Total: ${heapTotalMB} MB`); - console.log(` RSS: ${rssMB} MB`); - console.log(` External: ${externalMB} MB`); - console.log(` Array Buffers: ${arrayBuffersMB} MB`); + console.log(`📊 内存状态 [${level}]:`); + console.log(` Heap: ${heapUsedMB}/${heapTotalMB} MB`); + console.log(` RSS: ${rssMB} MB`); + console.log(` External: ${externalMB} MB`); } /** diff --git a/backend/utils/scanManager.js b/backend/utils/scanManager.js index e251e5e..b35dee1 100644 --- a/backend/utils/scanManager.js +++ b/backend/utils/scanManager.js @@ -1,6 +1,6 @@ /** - * 扫描状态管理器 - * 支持扫描的停止、继续和持久化 + * 扫描状态管理器(简化版) + * 只负责进度持久化,无暂停功能 */ const fs = require('fs'); @@ -8,17 +8,17 @@ const path = require('path'); class ScanManager { constructor() { - // 每个素材库的扫描状态(内存) this.scanStates = new Map(); - // 素材库路径映射(用于持久化) this.libraryPaths = new Map(); + this.saveTimers = new Map(); } /** - * 注册素材库路径(用于持久化) + * 注册素材库路径 */ registerLibraryPath(libraryId, libraryPath) { this.libraryPaths.set(libraryId, libraryPath); + this._restoreStateFromFile(libraryId); } /** @@ -31,15 +31,15 @@ class ScanManager { } /** - * 保存状态到文件(轻量:只保存关键信息) + * 保存状态到文件 */ saveState(libraryId) { const stateFile = this.getStateFilePath(libraryId); if (!stateFile) return; const state = this.scanStates.get(libraryId); + if (!state || state.status === 'idle') { - // 删除状态文件 try { if (fs.existsSync(stateFile)) { fs.unlinkSync(stateFile); @@ -49,19 +49,38 @@ class ScanManager { } try { + const dir = path.dirname(stateFile); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } + const saveData = { status: state.status, progress: state.progress, - pendingCount: state.pendingFiles?.length || 0, - // 只保存文件相对路径,不保存完整路径列表(太大) + startTime: state.startTime, savedAt: Date.now() }; + fs.writeFileSync(stateFile, JSON.stringify(saveData, null, 2)); } catch (e) { - console.error('Failed to save scan state:', e.message); + console.error('❌ 保存扫描状态失败:', e.message); } } + /** + * 定时保存(每5秒) + */ + _scheduleSave(libraryId) { + if (this.saveTimers.has(libraryId)) { + clearTimeout(this.saveTimers.get(libraryId)); + } + const timer = setTimeout(() => { + this.saveState(libraryId); + this.saveTimers.delete(libraryId); + }, 5000); + this.saveTimers.set(libraryId, timer); + } + /** * 从文件加载状态 */ @@ -71,7 +90,7 @@ class ScanManager { try { const data = JSON.parse(fs.readFileSync(stateFile, 'utf8')); - // 状态超过 24 小时视为过期 + // 24小时过期 if (Date.now() - data.savedAt > 24 * 60 * 60 * 1000) { fs.unlinkSync(stateFile); return null; @@ -83,48 +102,67 @@ class ScanManager { } /** - * 获取扫描状态(优先内存,其次文件) + * 从文件恢复状态 + */ + _restoreStateFromFile(libraryId) { + if (this.scanStates.has(libraryId)) { + return; + } + + const fileState = this.loadState(libraryId); + + if (fileState && fileState.status === 'scanning') { + this.scanStates.set(libraryId, { + status: fileState.status, + progress: fileState.progress, + startTime: fileState.startTime + }); + console.log(`🔄 恢复扫描状态: ${fileState.progress?.percent || 0}%`); + } + } + + /** + * 获取扫描状态 */ getState(libraryId) { - // 先检查内存中的状态 const memState = this.scanStates.get(libraryId); if (memState) return memState; - // 尝试从文件加载(应用重启后的恢复) const fileState = this.loadState(libraryId); - if (fileState && fileState.status === 'paused') { - // 重建内存状态(不含 pendingFiles,需要重新扫描确定) + if (fileState && fileState.status === 'scanning') { const restored = { - status: 'paused', + status: 'scanning', progress: fileState.progress, - pendingFiles: [], // 无法恢复完整列表,需要继续扫描时重新计算 - processedCount: fileState.progress?.current || 0, - abortController: { aborted: true }, - needsRescan: true // 标记需要重新扫描 + startTime: fileState.startTime }; this.scanStates.set(libraryId, restored); return restored; } - return { - status: 'idle', - progress: null, - pendingFiles: [], - processedCount: 0 - }; + return { status: 'idle', progress: null }; } /** * 开始扫描 */ - startScan(libraryId, totalFiles) { + startScan(libraryId, totalFiles, libraryPath) { + // 确保路径已注册 + if (libraryPath && !this.libraryPaths.has(libraryId)) { + this.libraryPaths.set(libraryId, libraryPath); + } + + if (this.saveTimers.has(libraryId)) { + clearTimeout(this.saveTimers.get(libraryId)); + this.saveTimers.delete(libraryId); + } + this.scanStates.set(libraryId, { status: 'scanning', progress: { current: 0, total: totalFiles, percent: 0 }, - pendingFiles: [], - processedCount: 0, - abortController: { aborted: false } + startTime: Date.now() }); + + this.saveState(libraryId); return this.scanStates.get(libraryId); } @@ -139,68 +177,15 @@ class ScanManager { total, percent: Math.round((current / total) * 100) }; - state.processedCount = current; + this._scheduleSave(libraryId); } } - /** - * 停止扫描 - */ - stopScan(libraryId, pendingFiles = []) { - const state = this.scanStates.get(libraryId); - if (state) { - state.status = 'paused'; - state.pendingFiles = pendingFiles; - state.abortController.aborted = true; - // 持久化状态 - this.saveState(libraryId); - console.log(`⏸️ Scan paused for ${libraryId}, ${pendingFiles.length} files pending`); - } - } - - /** - * 检查是否应该停止 - */ - shouldStop(libraryId) { - const state = this.scanStates.get(libraryId); - return state?.abortController?.aborted || false; - } - - /** - * 获取待处理文件 - */ - getPendingFiles(libraryId) { - const state = this.scanStates.get(libraryId); - return state?.pendingFiles || []; - } - - /** - * 恢复扫描 - */ - resumeScan(libraryId) { - const state = this.scanStates.get(libraryId); - if (state && state.status === 'paused') { - const pendingFiles = [...state.pendingFiles]; // 复制一份 - state.status = 'scanning'; - state.abortController = { aborted: false }; - state.pendingFiles = []; // 清空待处理列表 - console.log(`▶️ Scan resumed for ${libraryId}, ${pendingFiles.length} files to process`); - return pendingFiles; - } - return []; - } - /** * 完成扫描 */ completeScan(libraryId) { - const state = this.scanStates.get(libraryId); - if (state) { - state.status = 'idle'; - state.pendingFiles = []; - state.progress = null; - } - // 清除持久化状态 + this.scanStates.delete(libraryId); this.saveState(libraryId); } @@ -212,34 +197,50 @@ class ScanManager { return state?.status === 'scanning'; } - /** - * 是否已暂停 - */ - isPaused(libraryId) { - const state = this.scanStates.get(libraryId); - return state?.status === 'paused'; - } - /** * 清除素材库状态(删除素材库时调用) */ clearState(libraryId) { this.scanStates.delete(libraryId); + this.libraryPaths.delete(libraryId); + // 删除状态文件 + const stateFile = this.getStateFilePath(libraryId); + if (stateFile) { + try { + const fs = require('fs'); + if (fs.existsSync(stateFile)) { + fs.unlinkSync(stateFile); + } + } catch (e) { /* ignore */ } + } } /** - * 清除所有空闲状态(内存清理) + * 获取所有活跃状态 */ - cleanupIdleStates() { + getAllActiveStates() { + const activeStates = {}; for (const [libraryId, state] of this.scanStates.entries()) { - if (state.status === 'idle') { - this.scanStates.delete(libraryId); + if (state.status === 'scanning') { + activeStates[libraryId] = { + status: state.status, + progress: state.progress, + startTime: state.startTime + }; } } + return activeStates; + } + + /** + * 恢复所有素材库状态 + */ + restoreAllStates(libraries) { + for (const lib of libraries) { + this.registerLibraryPath(lib.id, lib.path); + } } } -// 单例 const scanManager = new ScanManager(); - module.exports = scanManager; diff --git a/backend/utils/scanner.js b/backend/utils/scanner.js index 02106c0..ec00be1 100644 --- a/backend/utils/scanner.js +++ b/backend/utils/scanner.js @@ -38,8 +38,7 @@ function ensureFolderChain(db, folderPath) { // 安全检查:确保 db 对象有 getFolderByPath 方法 if (typeof db.getFolderByPath !== 'function') { - console.error('[ensureFolderChain] Error: db.getFolderByPath is not a function'); - console.error('[ensureFolderChain] db object keys:', Object.keys(db)); + console.error('❌ db.getFolderByPath 不是函数'); return; } @@ -116,7 +115,7 @@ async function applyChangesFromEvents(libraryPath, db, events) { } results.added++; } catch (error) { - console.error(`Error processing added file ${file}:`, error.message); + console.error(`❌ 处理新增文件失败 ${file}:`, error.message); } } @@ -137,7 +136,7 @@ async function applyChangesFromEvents(libraryPath, db, events) { affectedFolders.add(folder); results.modified++; } catch (error) { - console.error(`Error processing changed file ${file}:`, error.message); + console.error(`❌ 处理修改文件失败 ${file}:`, error.message); } } @@ -158,7 +157,7 @@ async function applyChangesFromEvents(libraryPath, db, events) { } results.deleted++; } catch (error) { - console.error(`Error deleting file ${file}:`, error.message); + console.error(`❌ 删除文件失败 ${file}:`, error.message); } } @@ -173,7 +172,7 @@ async function applyChangesFromEvents(libraryPath, db, events) { if (parent && parent !== '.') affectedFolders.add(parent); results.foldersRemoved++; } catch (error) { - console.error(`Error deleting directory ${dir}:`, error.message); + console.error(`❌ 删除目录失败 ${dir}:`, error.message); } } @@ -183,14 +182,14 @@ async function applyChangesFromEvents(libraryPath, db, events) { try { db.updateFolderImageCount(folderPath); } catch (error) { - console.error(`Error updating folder count ${folderPath}:`, error.message); + console.error(`❌ 更新文件夹计数失败 ${folderPath}:`, error.message); } } }); return results; } catch (error) { - console.error('Error in applyChangesFromEvents:', error); + console.error('❌ 应用变化失败:', error.message); throw error; } } @@ -310,7 +309,7 @@ async function processImage(imagePath, libraryPath, db, dryRun = false) { return { status: 'processed', path: relativePath }; } catch (error) { - console.error('Error processing image:', imagePath, error); + console.error('❌ 处理图片失败:', path.basename(imagePath), error.message); return { status: 'error', path: imagePath, error: error.message }; } } @@ -338,20 +337,18 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume // 动态导入 p-limit const pLimit = (await import('p-limit')).default; - // 超激进内存控制:限制并发数为 2(防止 Sharp 内存泄漏) - const concurrency = 2; // 固定为 2,避免 Sharp 并发导致内存泄漏 + // 根据 CPU 核心数动态调整并发数 + const os = require('os'); + const cpuCount = os.cpus().length; + const concurrency = Math.max(4, Math.min(16, cpuCount - 1)); const limit = pLimit(concurrency); - console.log(`🚀 Starting scan with concurrency: ${concurrency} (memory-optimized)`); - if (resumeFiles && resumeFiles.length > 0) { // 继续扫描:使用待处理文件列表 files = resumeFiles; - console.log(`▶️ Resuming scan with ${files.length} pending files`); } else { // 新扫描:获取所有文件 files = await getAllImageFiles(libraryPath); - console.log(`Found ${files.length} images in library`); // Get folder structure const folders = await getFolderStructure(libraryPath); @@ -366,7 +363,7 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume // 初始化扫描状态 if (libraryId) { - scanManager.startScan(libraryId, total); + scanManager.startScan(libraryId, total, libraryPath); } const results = { @@ -381,7 +378,8 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume // 批量写入缓冲区 let writeBuffer = []; - const WRITE_BATCH_SIZE = 100; // 每 100 条写入一次数据库 + const WRITE_BATCH_SIZE = 50; // 每 50 条写入一次数据库(降低内存峰值) + const STREAM_BATCH_SIZE = 200; // 每批处理 200 个文件(流式处理) // 批量写入函数(事务) const batchWrite = db.db.transaction((items) => { @@ -394,11 +392,6 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume // 处理单个文件的包装函数 const processFile = async (file) => { - // 检查是否需要停止 - if (libraryId && scanManager.shouldStop(libraryId)) { - return { status: 'stopped', file }; - } - try { const result = await processImage(file, libraryPath, db, true); // true = dryRun (不直接写入DB) return result; @@ -407,71 +400,82 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume } }; - // 创建所有任务 - const tasks = files.map(file => limit(async () => { - // 如果已经停止,直接返回 - if (results.stopped) return; + // 流式处理:分批处理文件,避免一次性创建大量 Promise + for (let batchStart = 0; batchStart < total; batchStart += STREAM_BATCH_SIZE) { + const batchEnd = Math.min(batchStart + STREAM_BATCH_SIZE, total); + const batchFiles = files.slice(batchStart, batchEnd); - const result = await processFile(file); + // 处理当前批次 + const batchTasks = batchFiles.map(file => limit(async () => { + const result = await processFile(file); - if (result.status === 'stopped') { - results.stopped = true; - return; - } + // 更新统计 + if (result.status === 'processed') results.processed++; + else if (result.status === 'skipped') results.skipped++; + else if (result.status === 'error') results.errors++; - // 更新统计 - if (result.status === 'processed') results.processed++; - else if (result.status === 'skipped') results.skipped++; - else if (result.status === 'error') results.errors++; + // 添加到写入缓冲区 + if (result.status === 'processed') { + writeBuffer.push(result); - // 添加到写入缓冲区 - if (result.status === 'processed') { - writeBuffer.push(result); - - // 缓冲区满,执行批量写入 - if (writeBuffer.length >= WRITE_BATCH_SIZE) { - batchWrite(writeBuffer); - writeBuffer = []; - } - } - - processedCount++; - - // 报告进度 (每完成 10 个文件报告一次,避免过于频繁) - if (processedCount % 10 === 0 || processedCount === total) { - const current = processedCount; - - if (libraryId) { - scanManager.updateProgress(libraryId, current, total); + // 缓冲区满,执行批量写入 + if (writeBuffer.length >= WRITE_BATCH_SIZE) { + batchWrite(writeBuffer); + writeBuffer = []; // 清空缓冲区,释放内存 + } } - if (onProgress) { - const elapsed = Date.now() - startTime; - const avgTimePerImage = elapsed / current; - const remaining = total - current; - const estimatedTimeLeft = Math.round((remaining * avgTimePerImage) / 1000); + processedCount++; - onProgress({ - total, - current, - percent: Math.round((current / total) * 100), - currentFile: file, - estimatedTimeLeft, - canStop: true - }); + // 报告进度 (每完成 10 个文件报告一次) + if (processedCount % 10 === 0 || processedCount === total) { + const current = processedCount; + + if (libraryId) { + scanManager.updateProgress(libraryId, current, total); + } + + if (onProgress) { + const elapsed = Date.now() - startTime; + const avgTimePerImage = elapsed / current; + const remaining = total - current; + const estimatedTimeLeft = Math.round((remaining * avgTimePerImage) / 1000); + + onProgress({ + total, + current, + percent: Math.round((current / total) * 100), + currentFile: file, + estimatedTimeLeft + }); + } } + + return result; + })); + + // 等待当前批次完成 + await Promise.all(batchTasks); + + // 批次完成后,写入剩余缓冲区并释放内存 + if (writeBuffer.length > 0) { + batchWrite(writeBuffer); + writeBuffer = []; } - // 性能日志 - if (processedCount > 0 && processedCount % 1000 === 0) { + // 每1000个文件输出一次进度(减少日志) + if (processedCount % 1000 === 0) { const elapsed = (Date.now() - startTime) / 1000; const speed = processedCount / elapsed; - console.log(`⚡ Performance: ${speed.toFixed(1)} images/sec, ${processedCount}/${total} completed`); + const percent = ((processedCount / total) * 100).toFixed(1); + console.log(`⚡ ${processedCount}/${total} (${percent}%) | ${speed.toFixed(1)} 张/秒`); } - })); - - // 等待所有任务完成 - await Promise.all(tasks); + + // 每 1000 个文件触发一次 GC + if (processedCount > 0 && processedCount % 1000 === 0 && global.gc) { + global.gc(); + } + } // 写入剩余的缓冲区数据 if (writeBuffer.length > 0) { @@ -479,16 +483,8 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume writeBuffer = []; } - // 处理停止情况 - if (results.stopped) { - const pendingFiles = files.slice(processedCount); - scanManager.stopScan(libraryId, pendingFiles); - console.log(`⏸️ Scan stopped at ${processedCount}/${total}, ${pendingFiles.length} files pending`); - return results; - } - const totalTime = (Date.now() - startTime) / 1000; - console.log(`✅ Scan completed in ${totalTime.toFixed(1)}s, speed: ${(total / totalTime).toFixed(1)} images/sec`); + console.log(`✅ 扫描完成: ${total} 个文件 (${totalTime.toFixed(1)}秒, ${(total / totalTime).toFixed(1)} 张/秒)`); // Update folder image counts db.updateAllFolderCounts(); @@ -497,11 +493,9 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume if (libraryId) { scanManager.completeScan(libraryId); } - - console.log('Scan complete:', results); return results; } catch (error) { - console.error('Error scanning library:', error); + console.error('❌ 扫描失败:', error.message); if (libraryId) { scanManager.completeScan(libraryId); } @@ -534,17 +528,14 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr const toCheck = [...currentPaths].filter(p => dbPaths.has(p)); let toDelete = [...dbPaths].filter(p => !currentPaths.has(p)); - console.log(`Sync: ${toAdd.length} new, ${toCheck.length} to check, ${toDelete.length} deleted`); + console.log(`🔄 同步: +${toAdd.length} 检查${toCheck.length} -${toDelete.length}`); // 安全检查:如果要删除的文件数量超过数据库中文件的50%,可能是路径匹配问题 const dbImageCount = dbPaths.size; if (toDelete.length > 0 && dbImageCount > 0) { const deleteRatio = toDelete.length / dbImageCount; if (deleteRatio > 0.5 && toDelete.length > 10) { - console.warn(`⚠️ 安全检查:要删除 ${toDelete.length}/${dbImageCount} (${(deleteRatio * 100).toFixed(1)}%) 的文件,这可能是路径匹配问题,跳过删除操作`); - console.log('示例 currentPath:', [...currentPaths].slice(0, 3)); - console.log('示例 dbPath:', [...dbPaths].slice(0, 3)); - // 清空 toDelete,不执行删除 + console.warn(`⚠️ 安全检查: 跳过删除 ${toDelete.length}/${dbImageCount} 个文件 (${(deleteRatio * 100).toFixed(1)}%)`); toDelete = []; } } @@ -584,7 +575,9 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr return existing.file_hash !== currentHash; }).length; - console.log(`Found ${modifiedCount} modified files (skipped, hash unchanged)`); + if (modifiedCount > 0) { + console.log(`📝 发现 ${modifiedCount} 个修改文件`); + } // Delete removed files for (const relativePath of toDelete) { @@ -594,7 +587,7 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr // Rebuild folder structure if there are changes or forced if (toAdd.length > 0 || toDelete.length > 0 || forceRebuildFolders) { - console.log('Rebuilding folder structure...'); + console.log('📂 重建文件夹结构...'); // Get current folder structure from file system const currentFolders = await getFolderStructure(libraryPath); @@ -618,10 +611,11 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr db.deleteFolder(folder.path); }); - console.log(`Folders: +${foldersToAdd.length}, -${foldersToDelete.length}`); + if (foldersToAdd.length > 0 || foldersToDelete.length > 0) { + console.log(`📂 文件夹变化: +${foldersToAdd.length} -${foldersToDelete.length}`); + } // Update folder image counts - console.log('Updating folder image counts...'); const affectedFolders = new Set(); // Collect all affected folders (including parent folders) @@ -641,12 +635,10 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr affectedFolders.forEach(folderPath => { db.updateFolderImageCount(folderPath); }); - - console.log(`Updated ${affectedFolders.size} folder counts`); } const totalTime = (Date.now() - startTime) / 1000; - console.log(`✅ Sync completed in ${totalTime.toFixed(1)}s`); + console.log(`✅ 同步完成 (${totalTime.toFixed(1)}秒)`); return { added: toAdd.length, @@ -654,7 +646,7 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr deleted: toDelete.length }; } catch (error) { - console.error('Error syncing library:', error); + console.error('❌ 同步失败:', error.message); throw error; } } @@ -687,7 +679,7 @@ async function quickSync(libraryPath, db) { if (toDelete.length > 0 && dbImageCount > 0) { const deleteRatio = toDelete.length / dbImageCount; if (deleteRatio > 0.5 && toDelete.length > 10) { - console.warn(`⚠️ 安全检查:跳过删除 ${toDelete.length} 个文件`); + console.warn(`⚠️ 跳过删除 ${toDelete.length} 个文件`); toDelete = []; } } @@ -703,7 +695,7 @@ async function quickSync(libraryPath, db) { } await processImage(fullPath, libraryPath, db); } catch (err) { - console.error(`Error adding ${relativePath}:`, err.message); + console.error(`❌ 添加失败 ${relativePath}:`, err.message); } } @@ -719,7 +711,7 @@ async function quickSync(libraryPath, db) { const elapsed = Date.now() - startTime; if (toAdd.length > 0 || toDelete.length > 0) { - console.log(`Quick sync: +${toAdd.length} -${toDelete.length} (${elapsed}ms)`); + console.log(`⚡ 快速同步: +${toAdd.length} -${toDelete.length} (${elapsed}ms)`); } return { added: toAdd.length, deleted: toDelete.length }; diff --git a/backend/utils/thumbnail.js b/backend/utils/thumbnail.js index 21d7fb9..45d4b98 100644 --- a/backend/utils/thumbnail.js +++ b/backend/utils/thumbnail.js @@ -13,8 +13,6 @@ sharp.cache({ // 设置并发限制 sharp.concurrency(1); // 一次只处理 1 张图片 -console.log('[Sharp] Memory-optimized configuration applied: cache=50MB, concurrency=1'); - // 支持的文件格式(确定可以生成缩略图的) const IMAGE_FORMATS = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'tiff', 'tif', 'avif', 'heif', 'heic', 'svg']; @@ -248,13 +246,6 @@ async function generateThumbnail(inputPath, outputPath, targetHeight = 200) { const stats = fs.statSync(outputPath); const finalSize = stats.size; - // 可选:输出详细信息(每100张输出一次,避免日志过多) - const shouldLog = Math.random() < 0.01; // 1% 概率输出 - if (shouldLog) { - const sizeKB = (finalSize / 1024).toFixed(1); - console.log(`📸 Thumbnail: ${config.megaPixels}MP → ${config.width}x${config.height} (${sizeKB}KB, Q${quality}, ratio ${downscaleRatio.toFixed(1)}x)`); - } - return { width: config.width, height: config.height, @@ -324,8 +315,6 @@ async function generateImageThumbnails(imagePath, libraryPath) { const hash = crypto.createHash('md5').update(relativePath).digest('hex'); const fileType = getFileType(imagePath); - console.log(`📝 Processing file: ${path.basename(imagePath)}, type: ${fileType}`); - // Sharding: use first 2 chars of hash for subdirectories (e.g. /ab/) const shard1 = hash.slice(0, 2); // 1-level sharding: .flypic/thumbnails/ab/hash.webp @@ -342,34 +331,27 @@ async function generateImageThumbnails(imagePath, libraryPath) { thumbnailResult = await generateThumbnail(imagePath, out480, 480); } else if (fileType === 'video') { // 视频:尝试提取封面 - console.log(`🎬 Extracting video thumbnail for: ${path.basename(imagePath)}`); thumbnailResult = await extractVideoThumbnail(imagePath, out480); // 如果提取失败,生成占位图 if (!thumbnailResult) { - console.log(`🎬 Generating video placeholder for: ${path.basename(imagePath)}`); thumbnailResult = await generatePlaceholderThumbnail(out480, 'video', ext); } } else if (fileType === 'design') { // 设计文件:尝试提取嵌入缩略图(仅 PSD) if (ext.toLowerCase() === 'psd') { - console.log(`🎨 Extracting PSD thumbnail for: ${path.basename(imagePath)}`); thumbnailResult = await extractPSDThumbnail(imagePath, out480); } // 如果提取失败或不是 PSD,生成占位图 if (!thumbnailResult) { - console.log(`🎨 Generating design placeholder for: ${path.basename(imagePath)}`); thumbnailResult = await generatePlaceholderThumbnail(out480, 'design', ext); } } else { // 其他类型(音频/文档/未知):生成占位图 - console.log(`📦 Generating ${fileType} placeholder for: ${path.basename(imagePath)}`); thumbnailResult = await generatePlaceholderThumbnail(out480, fileType, ext); } - console.log(`✅ Thumbnail generated: ${path.basename(out480)}, ${thumbnailResult.width}x${thumbnailResult.height}, ${(thumbnailResult.size / 1024).toFixed(1)}KB`); - // 返回相对于 libraryPath 的路径(包含 .flypic 前缀) const thumbnailPath = path.relative(libraryPath, out480).replace(/\\/g, '/'); @@ -427,7 +409,6 @@ async function extractPSDThumbnail(psdPath, outputPath) { // 先获取原始缩略图尺寸 const metadata = await sharp(jpegData).metadata(); - console.log(` 📐 PSD embedded thumbnail: ${metadata.width}x${metadata.height}`); // 使用高质量缩放,保持宽高比 const aspectRatio = metadata.width / metadata.height; @@ -477,7 +458,6 @@ async function extractPSDThumbnail(psdPath, outputPath) { .toFile(outputPath); const stats = fs.statSync(outputPath); - console.log(` ✅ PSD thumbnail extracted: ${(stats.size / 1024).toFixed(1)}KB`); return { width: targetWidth, height: targetHeight, @@ -524,7 +504,6 @@ async function extractVideoThumbnail(videoPath, outputPath) { if (fs.existsSync(tempJpg)) { // 先获取实际尺寸 const metadata = await sharp(tempJpg).metadata(); - console.log(` 📐 Video frame: ${metadata.width}x${metadata.height}`); // 保持宽高比缩放到 480 高度 const aspectRatio = metadata.width / metadata.height; @@ -544,7 +523,6 @@ async function extractVideoThumbnail(videoPath, outputPath) { fs.unlinkSync(tempJpg); // 删除临时 JPG const stats = fs.statSync(outputPath); - console.log(` ✅ Video thumbnail extracted: ${targetWidth}x${targetHeight}, ${(stats.size / 1024).toFixed(1)}KB`); return { width: targetWidth, height: targetHeight, diff --git a/flypic/app/server/database/db.js b/flypic/app/server/database/db.js index edbeb1a..5ed1457 100644 --- a/flypic/app/server/database/db.js +++ b/flypic/app/server/database/db.js @@ -13,11 +13,9 @@ class LibraryDatabase { fs.mkdirSync(this.flypicDir, { recursive: true }); } - // Create thumbnails directory (480px 与 Billfish 一致) + // Create thumbnails directory (使用分片结构: .flypic/thumbnails/ab/hash.webp) const thumbDir = path.join(this.flypicDir, 'thumbnails'); - const thumbDir480 = path.join(thumbDir, '480'); if (!fs.existsSync(thumbDir)) fs.mkdirSync(thumbDir, { recursive: true }); - if (!fs.existsSync(thumbDir480)) fs.mkdirSync(thumbDir480, { recursive: true }); this.db = new Database(this.dbPath); @@ -29,6 +27,15 @@ class LibraryDatabase { this.db.pragma('mmap_size = 268435456'); // 256MB 内存映射 this.initTables(); + + // 启动 WAL 定期 checkpoint(每 5 分钟) + this.walCheckpointInterval = setInterval(() => { + try { + this.db.pragma('wal_checkpoint(PASSIVE)'); + } catch (e) { + console.warn('[DB] WAL checkpoint warning:', e.message); + } + }, 300000); // 5 分钟 } initTables() { @@ -165,8 +172,11 @@ class LibraryDatabase { } getAllImages() { - const stmt = this.db.prepare('SELECT * FROM images ORDER BY created_at DESC'); - return stmt.all(); + // ⚠️ 警告:此方法会加载所有图片到内存,仅用于调试! + // 生产环境请使用 searchImages() 或流式查询 + console.warn('[DB] WARNING: getAllImages() loads all data into memory. Use searchImages() instead!'); + const stmt = this.db.prepare('SELECT * FROM images ORDER BY created_at DESC LIMIT 1000'); + return stmt.all(); // 限制最多 1000 条 } searchImages(keywords, filters = {}, pagination = null) { @@ -220,8 +230,9 @@ class LibraryDatabase { if (pagination && typeof pagination.offset === 'number' && typeof pagination.limit === 'number') { const timings = {}; - // 先获取数据(快速) - const query = `SELECT * ${baseQuery} ORDER BY created_at DESC LIMIT ? OFFSET ?`; + // 只选择必要字段,减少内存占用 + const essentialFields = 'id, path, filename, size, format, width, height, thumbnail_path, folder'; + const query = `SELECT ${essentialFields} ${baseQuery} ORDER BY created_at DESC LIMIT ? OFFSET ?`; const paginatedParams = [...params, pagination.limit, pagination.offset]; let queryStart = Date.now(); @@ -393,6 +404,19 @@ class LibraryDatabase { } close() { + // 清理 WAL checkpoint 定时器 + if (this.walCheckpointInterval) { + clearInterval(this.walCheckpointInterval); + this.walCheckpointInterval = null; + } + + // 执行最后一次 checkpoint + try { + this.db.pragma('wal_checkpoint(TRUNCATE)'); + } catch (e) { + console.warn('[DB] Final WAL checkpoint warning:', e.message); + } + this.db.close(); } } diff --git a/flypic/app/server/database/dbPool.js b/flypic/app/server/database/dbPool.js index d71fe5b..3749f62 100644 --- a/flypic/app/server/database/dbPool.js +++ b/flypic/app/server/database/dbPool.js @@ -6,6 +6,12 @@ const LibraryDatabase = require('./db'); */ class DatabasePool { constructor() { + // 单例模式:确保只有一个实例,避免多个定时器 + if (DatabasePool.instance) { + return DatabasePool.instance; + } + DatabasePool.instance = this; + this.connections = new Map(); // libraryPath -> { db, lastUsed, refCount } this.maxIdleTime = 60000; // 60秒未使用则关闭 this.cleanupInterval = null; @@ -16,20 +22,12 @@ class DatabasePool { /** * 获取数据库连接(复用或创建) - * 优化:同时只保持一个活跃连接 + * 优化:严格限制最大1个活跃连接 */ acquire(libraryPath) { let conn = this.connections.get(libraryPath); if (!conn) { - // 如果已有其他连接且引用计数为0,先关闭它们 - for (const [path, existingConn] of this.connections.entries()) { - if (existingConn.refCount === 0) { - console.log(`[DBPool] Auto-closing idle connection: ${path}`); - this.close(path); - } - } - // 创建新连接 const db = new LibraryDatabase(libraryPath); conn = { @@ -38,7 +36,6 @@ class DatabasePool { refCount: 0 }; this.connections.set(libraryPath, conn); - console.log(`[DBPool] Created new connection for: ${libraryPath}`); } // 更新使用时间和引用计数 @@ -69,23 +66,19 @@ class DatabasePool { // 强制设置引用计数为0 conn.refCount = 0; - // 关闭数据库连接 + // 执行 checkpoint 确保 WAL 写入主数据库 if (conn.db && conn.db.db) { - // 执行 checkpoint 确保 WAL 写入主数据库 try { conn.db.db.pragma('wal_checkpoint(TRUNCATE)'); } catch (e) { console.warn(`[DBPool] WAL checkpoint warning:`, e.message); } - - // 关闭连接 - conn.db.close(); } + conn.db.close(); this.connections.delete(libraryPath); - console.log(`[DBPool] Closed connection for: ${libraryPath}`); } catch (error) { - console.error(`[DBPool] Error closing connection:`, error); + console.error(`❌ 关闭数据库连接失败:`, error.message); // 即使出错也删除引用 this.connections.delete(libraryPath); } @@ -96,26 +89,43 @@ class DatabasePool { * 关闭所有连接 */ closeAll() { - for (const [path, conn] of this.connections.entries()) { - try { - conn.db.close(); - console.log(`[DBPool] Closed connection for: ${path}`); - } catch (error) { - console.error(`[DBPool] Error closing connection:`, error); - } - } - this.connections.clear(); - + // 先清理定时器,避免在关闭过程中触发清理 if (this.cleanupInterval) { clearInterval(this.cleanupInterval); this.cleanupInterval = null; } + + for (const [path, conn] of this.connections.entries()) { + try { + // 执行 checkpoint 确保 WAL 写入主数据库 + if (conn.db && conn.db.db) { + try { + conn.db.db.pragma('wal_checkpoint(TRUNCATE)'); + } catch (e) { + console.warn(`[DBPool] WAL checkpoint warning:`, e.message); + } + } + conn.db.close(); + } catch (error) { + console.error(`❌ 关闭数据库连接失败:`, error.message); + } + } + this.connections.clear(); + } + + /** + * 强制关闭所有连接(用于紧急清理) + * 与 closeAll() 相同,但提供明确的语义 + */ + forceCloseAll() { + this.closeAll(); } /** * 启动定期清理空闲连接 */ startCleanup() { + // 更频繁的检查(每10秒) this.cleanupInterval = setInterval(() => { const now = Date.now(); const toClose = []; @@ -130,9 +140,14 @@ class DatabasePool { toClose.forEach(path => this.close(path)); if (toClose.length > 0) { - console.log(`[DBPool] Cleaned up ${toClose.length} idle connections`); + // 关闭连接后立即强制 GC + if (global.gc) { + for (let i = 0; i < 3; i++) { + global.gc(); + } + } } - }, 30000); // 每30秒检查一次 + }, 10000); // 每10秒检查一次(更频繁) } /** @@ -147,7 +162,28 @@ class DatabasePool { idleTime: Date.now() - conn.lastUsed }); } - return status; + return { + connections: status, + totalConnections: this.connections.size, + maxConnections: this.maxConnections, + maxIdleTime: this.maxIdleTime + }; + } + + /** + * 实现 clear() 方法以支持 CleanupManager 注册 + */ + clear() { + // 清理空闲连接 + const toClose = []; + + for (const [path, conn] of this.connections.entries()) { + if (conn.refCount === 0) { + toClose.push(path); + } + } + + toClose.forEach(path => this.close(path)); } } diff --git a/flypic/app/server/package-lock.json b/flypic/app/server/package-lock.json index ea86445..6cdaed5 100644 --- a/flypic/app/server/package-lock.json +++ b/flypic/app/server/package-lock.json @@ -580,23 +580,23 @@ } }, "node_modules/body-parser": { - "version": "1.20.3", - "resolved": "https://registry.npmmirror.com/body-parser/-/body-parser-1.20.3.tgz", - "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "version": "1.20.4", + "resolved": "https://registry.npmmirror.com/body-parser/-/body-parser-1.20.4.tgz", + "integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==", "license": "MIT", "dependencies": { - "bytes": "3.1.2", + "bytes": "~3.1.2", "content-type": "~1.0.5", "debug": "2.6.9", "depd": "2.0.0", - "destroy": "1.2.0", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "on-finished": "2.4.1", - "qs": "6.13.0", - "raw-body": "2.5.2", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.14.0", + "raw-body": "~2.5.3", "type-is": "~1.6.18", - "unpipe": "1.0.0" + "unpipe": "~1.0.0" }, "engines": { "node": ">= 0.8", @@ -786,18 +786,18 @@ } }, "node_modules/cookie": { - "version": "0.7.1", - "resolved": "https://registry.npmmirror.com/cookie/-/cookie-0.7.1.tgz", - "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", + "version": "0.7.2", + "resolved": "https://registry.npmmirror.com/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", "license": "MIT", "engines": { "node": ">= 0.6" } }, "node_modules/cookie-signature": { - "version": "1.0.6", - "resolved": "https://registry.npmmirror.com/cookie-signature/-/cookie-signature-1.0.6.tgz", - "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==", + "version": "1.0.7", + "resolved": "https://registry.npmmirror.com/cookie-signature/-/cookie-signature-1.0.7.tgz", + "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", "license": "MIT" }, "node_modules/cors": { @@ -993,15 +993,6 @@ "node": ">=10.0.0" } }, - "node_modules/engine.io/node_modules/cookie": { - "version": "0.7.2", - "resolved": "https://registry.npmmirror.com/cookie/-/cookie-0.7.2.tgz", - "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, "node_modules/engine.io/node_modules/debug": { "version": "4.3.7", "resolved": "https://registry.npmmirror.com/debug/-/debug-4.3.7.tgz", @@ -1080,39 +1071,39 @@ } }, "node_modules/express": { - "version": "4.21.2", - "resolved": "https://registry.npmmirror.com/express/-/express-4.21.2.tgz", - "integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==", + "version": "4.22.1", + "resolved": "https://registry.npmmirror.com/express/-/express-4.22.1.tgz", + "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", "license": "MIT", "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", - "body-parser": "1.20.3", - "content-disposition": "0.5.4", + "body-parser": "~1.20.3", + "content-disposition": "~0.5.4", "content-type": "~1.0.4", - "cookie": "0.7.1", - "cookie-signature": "1.0.6", + "cookie": "~0.7.1", + "cookie-signature": "~1.0.6", "debug": "2.6.9", "depd": "2.0.0", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "etag": "~1.8.1", - "finalhandler": "1.3.1", - "fresh": "0.5.2", - "http-errors": "2.0.0", + "finalhandler": "~1.3.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.0", "merge-descriptors": "1.0.3", "methods": "~1.1.2", - "on-finished": "2.4.1", + "on-finished": "~2.4.1", "parseurl": "~1.3.3", - "path-to-regexp": "0.1.12", + "path-to-regexp": "~0.1.12", "proxy-addr": "~2.0.7", - "qs": "6.13.0", + "qs": "~6.14.0", "range-parser": "~1.2.1", "safe-buffer": "5.2.1", - "send": "0.19.0", - "serve-static": "1.16.2", + "send": "~0.19.0", + "serve-static": "~1.16.2", "setprototypeof": "1.2.0", - "statuses": "2.0.1", + "statuses": "~2.0.1", "type-is": "~1.6.18", "utils-merge": "1.0.1", "vary": "~1.1.2" @@ -1144,17 +1135,17 @@ } }, "node_modules/finalhandler": { - "version": "1.3.1", - "resolved": "https://registry.npmmirror.com/finalhandler/-/finalhandler-1.3.1.tgz", - "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "version": "1.3.2", + "resolved": "https://registry.npmmirror.com/finalhandler/-/finalhandler-1.3.2.tgz", + "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", "license": "MIT", "dependencies": { "debug": "2.6.9", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", - "on-finished": "2.4.1", + "on-finished": "~2.4.1", "parseurl": "~1.3.3", - "statuses": "2.0.1", + "statuses": "~2.0.2", "unpipe": "~1.0.0" }, "engines": { @@ -1346,19 +1337,23 @@ } }, "node_modules/http-errors": { - "version": "2.0.0", - "resolved": "https://registry.npmmirror.com/http-errors/-/http-errors-2.0.0.tgz", - "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", "license": "MIT", "dependencies": { - "depd": "2.0.0", - "inherits": "2.0.4", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "toidentifier": "1.0.1" + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" }, "engines": { "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/iconv-lite": { @@ -1917,12 +1912,12 @@ } }, "node_modules/qs": { - "version": "6.13.0", - "resolved": "https://registry.npmmirror.com/qs/-/qs-6.13.0.tgz", - "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "version": "6.14.0", + "resolved": "https://registry.npmmirror.com/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", "license": "BSD-3-Clause", "dependencies": { - "side-channel": "^1.0.6" + "side-channel": "^1.1.0" }, "engines": { "node": ">=0.6" @@ -1941,15 +1936,15 @@ } }, "node_modules/raw-body": { - "version": "2.5.2", - "resolved": "https://registry.npmmirror.com/raw-body/-/raw-body-2.5.2.tgz", - "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "version": "2.5.3", + "resolved": "https://registry.npmmirror.com/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", "license": "MIT", "dependencies": { - "bytes": "3.1.2", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "unpipe": "1.0.0" + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" }, "engines": { "node": ">= 0.8" @@ -2035,6 +2030,98 @@ } }, "node_modules/send": { + "version": "0.19.1", + "resolved": "https://registry.npmmirror.com/send/-/send-0.19.1.tgz", + "integrity": "sha512-p4rRk4f23ynFEfcD9LA0xRYngj+IyGiEYyqqOak8kaN0TvNmuxC2dcVeBn62GpCeR2CpWqyHCNScTP91QbAVFg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/send/node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/serve-static": { + "version": "1.16.2", + "resolved": "https://registry.npmmirror.com/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.19.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/serve-static/node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/serve-static/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/serve-static/node_modules/send": { "version": "0.19.0", "resolved": "https://registry.npmmirror.com/send/-/send-0.19.0.tgz", "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", @@ -2058,7 +2145,7 @@ "node": ">= 0.8.0" } }, - "node_modules/send/node_modules/encodeurl": { + "node_modules/serve-static/node_modules/send/node_modules/encodeurl": { "version": "1.0.2", "resolved": "https://registry.npmmirror.com/encodeurl/-/encodeurl-1.0.2.tgz", "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", @@ -2067,25 +2154,13 @@ "node": ">= 0.8" } }, - "node_modules/send/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT" - }, - "node_modules/serve-static": { - "version": "1.16.2", - "resolved": "https://registry.npmmirror.com/serve-static/-/serve-static-1.16.2.tgz", - "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "node_modules/serve-static/node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", "license": "MIT", - "dependencies": { - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "parseurl": "~1.3.3", - "send": "0.19.0" - }, "engines": { - "node": ">= 0.8.0" + "node": ">= 0.8" } }, "node_modules/setprototypeof": { @@ -2416,9 +2491,9 @@ "license": "MIT" }, "node_modules/statuses": { - "version": "2.0.1", - "resolved": "https://registry.npmmirror.com/statuses/-/statuses-2.0.1.tgz", - "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "version": "2.0.2", + "resolved": "https://registry.npmmirror.com/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", "license": "MIT", "engines": { "node": ">= 0.8" diff --git a/flypic/app/server/package.json b/flypic/app/server/package.json index 76751a2..9956ce7 100644 --- a/flypic/app/server/package.json +++ b/flypic/app/server/package.json @@ -4,8 +4,8 @@ "description": "FlyPic backend server", "main": "server.js", "scripts": { - "dev": "cross-env PORT=15002 nodemon server.js", - "start": "node server.js" + "dev": "cross-env PORT=15002 nodemon --expose-gc server.js", + "start": "node --expose-gc server.js" }, "dependencies": { "better-sqlite3": "^9.2.2", diff --git a/flypic/app/server/public/assets/index-CGwCzICz.js b/flypic/app/server/public/assets/index-CGwCzICz.js deleted file mode 100644 index c148ef5..0000000 --- a/flypic/app/server/public/assets/index-CGwCzICz.js +++ /dev/null @@ -1,224 +0,0 @@ -(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();var Es=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function su(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var gf={exports:{}},$o={},yf={exports:{}},Se={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var ms=Symbol.for("react.element"),Sm=Symbol.for("react.portal"),bm=Symbol.for("react.fragment"),Em=Symbol.for("react.strict_mode"),Cm=Symbol.for("react.profiler"),Nm=Symbol.for("react.provider"),Rm=Symbol.for("react.context"),Tm=Symbol.for("react.forward_ref"),Om=Symbol.for("react.suspense"),Im=Symbol.for("react.memo"),Am=Symbol.for("react.lazy"),fc=Symbol.iterator;function jm(e){return e===null||typeof e!="object"?null:(e=fc&&e[fc]||e["@@iterator"],typeof e=="function"?e:null)}var vf={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},wf=Object.assign,xf={};function vi(e,t,n){this.props=e,this.context=t,this.refs=xf,this.updater=n||vf}vi.prototype.isReactComponent={};vi.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};vi.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _f(){}_f.prototype=vi.prototype;function ou(e,t,n){this.props=e,this.context=t,this.refs=xf,this.updater=n||vf}var au=ou.prototype=new _f;au.constructor=ou;wf(au,vi.prototype);au.isPureReactComponent=!0;var hc=Array.isArray,kf=Object.prototype.hasOwnProperty,lu={current:null},Sf={key:!0,ref:!0,__self:!0,__source:!0};function bf(e,t,n){var r,i={},s=null,o=null;if(t!=null)for(r in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(s=""+t.key),t)kf.call(t,r)&&!Sf.hasOwnProperty(r)&&(i[r]=t[r]);var a=arguments.length-2;if(a===1)i.children=n;else if(1>>1,F=H[z];if(0>>1;zi(D,ee))lei(de,D)?(H[z]=de,H[le]=ee,z=le):(H[z]=D,H[B]=ee,z=B);else if(lei(de,ee))H[z]=de,H[le]=ee,z=le;else break e}}return U}function i(H,U){var ee=H.sortIndex-U.sortIndex;return ee!==0?ee:H.id-U.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;e.unstable_now=function(){return s.now()}}else{var o=Date,a=o.now();e.unstable_now=function(){return o.now()-a}}var l=[],d=[],p=1,y=null,x=3,g=!1,m=!1,u=!1,v=typeof setTimeout=="function"?setTimeout:null,c=typeof clearTimeout=="function"?clearTimeout:null,h=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function w(H){for(var U=n(d);U!==null;){if(U.callback===null)r(d);else if(U.startTime<=H)r(d),U.sortIndex=U.expirationTime,t(l,U);else break;U=n(d)}}function k(H){if(u=!1,w(H),!m)if(n(l)!==null)m=!0,ce(b);else{var U=n(d);U!==null&&Q(k,U.startTime-H)}}function b(H,U){m=!1,u&&(u=!1,c(P),P=-1),g=!0;var ee=x;try{for(w(U),y=n(l);y!==null&&(!(y.expirationTime>U)||H&&!J());){var z=y.callback;if(typeof z=="function"){y.callback=null,x=y.priorityLevel;var F=z(y.expirationTime<=U);U=e.unstable_now(),typeof F=="function"?y.callback=F:y===n(l)&&r(l),w(U)}else r(l);y=n(l)}if(y!==null)var A=!0;else{var B=n(d);B!==null&&Q(k,B.startTime-U),A=!1}return A}finally{y=null,x=ee,g=!1}}var N=!1,T=null,P=-1,O=5,M=-1;function J(){return!(e.unstable_now()-MH||125z?(H.sortIndex=ee,t(d,H),n(l)===null&&H===n(d)&&(u?(c(P),P=-1):u=!0,Q(k,ee-z))):(H.sortIndex=F,t(l,H),m||g||(m=!0,ce(b))),H},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(H){var U=x;return function(){var ee=x;x=U;try{return H.apply(this,arguments)}finally{x=ee}}}})(Tf);Rf.exports=Tf;var Hm=Rf.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Vm=Z,Ct=Hm;function ae(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Qa=Object.prototype.hasOwnProperty,qm=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,mc={},gc={};function Km(e){return Qa.call(gc,e)?!0:Qa.call(mc,e)?!1:qm.test(e)?gc[e]=!0:(mc[e]=!0,!1)}function Xm(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Ym(e,t,n,r){if(t===null||typeof t>"u"||Xm(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function ht(e,t,n,r,i,s,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=i,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=s,this.removeEmptyString=o}var et={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){et[e]=new ht(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];et[t]=new ht(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){et[e]=new ht(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){et[e]=new ht(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){et[e]=new ht(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){et[e]=new ht(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){et[e]=new ht(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){et[e]=new ht(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){et[e]=new ht(e,5,!1,e.toLowerCase(),null,!1,!1)});var cu=/[\-:]([a-z])/g;function du(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(cu,du);et[t]=new ht(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(cu,du);et[t]=new ht(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(cu,du);et[t]=new ht(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){et[e]=new ht(e,1,!1,e.toLowerCase(),null,!1,!1)});et.xlinkHref=new ht("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){et[e]=new ht(e,1,!1,e.toLowerCase(),null,!0,!0)});function fu(e,t,n,r){var i=et.hasOwnProperty(t)?et[t]:null;(i!==null?i.type!==0:r||!(2a||i[o]!==s[a]){var l=` -`+i[o].replace(" at new "," at ");return e.displayName&&l.includes("")&&(l=l.replace("",e.displayName)),l}while(1<=o&&0<=a);break}}}finally{ma=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?Pi(e):""}function Zm(e){switch(e.tag){case 5:return Pi(e.type);case 16:return Pi("Lazy");case 13:return Pi("Suspense");case 19:return Pi("SuspenseList");case 0:case 2:case 15:return e=ga(e.type,!1),e;case 11:return e=ga(e.type.render,!1),e;case 1:return e=ga(e.type,!0),e;default:return""}}function tl(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Hr:return"Fragment";case Wr:return"Portal";case Ga:return"Profiler";case hu:return"StrictMode";case Ja:return"Suspense";case el:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Af:return(e.displayName||"Context")+".Consumer";case If:return(e._context.displayName||"Context")+".Provider";case pu:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case mu:return t=e.displayName||null,t!==null?t:tl(e.type)||"Memo";case Wn:t=e._payload,e=e._init;try{return tl(e(t))}catch{}}return null}function Qm(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return tl(t);case 8:return t===hu?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function or(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function zf(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Gm(e){var t=zf(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var i=n.get,s=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(o){r=""+o,s.call(this,o)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Rs(e){e._valueTracker||(e._valueTracker=Gm(e))}function Lf(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=zf(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function mo(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function nl(e,t){var n=t.checked;return Ue({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function vc(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=or(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Pf(e,t){t=t.checked,t!=null&&fu(e,"checked",t,!1)}function rl(e,t){Pf(e,t);var n=or(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?il(e,t.type,n):t.hasOwnProperty("defaultValue")&&il(e,t.type,or(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function wc(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function il(e,t,n){(t!=="number"||mo(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Fi=Array.isArray;function ni(e,t,n,r){if(e=e.options,t){t={};for(var i=0;i"+t.valueOf().toString()+"",t=Ts.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Gi(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Ui={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Jm=["Webkit","ms","Moz","O"];Object.keys(Ui).forEach(function(e){Jm.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Ui[t]=Ui[e]})});function Bf(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Ui.hasOwnProperty(e)&&Ui[e]?(""+t).trim():t+"px"}function Uf(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,i=Bf(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,i):e[n]=i}}var e0=Ue({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function al(e,t){if(t){if(e0[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ae(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ae(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ae(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ae(62))}}function ll(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var ul=null;function gu(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var cl=null,ri=null,ii=null;function kc(e){if(e=vs(e)){if(typeof cl!="function")throw Error(ae(280));var t=e.stateNode;t&&(t=Ko(t),cl(e.stateNode,e.type,t))}}function $f(e){ri?ii?ii.push(e):ii=[e]:ri=e}function Wf(){if(ri){var e=ri,t=ii;if(ii=ri=null,kc(e),t)for(e=0;e>>=0,e===0?32:31-(d0(e)/f0|0)|0}var Os=64,Is=4194304;function Di(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function wo(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,i=e.suspendedLanes,s=e.pingedLanes,o=n&268435455;if(o!==0){var a=o&~i;a!==0?r=Di(a):(s&=o,s!==0&&(r=Di(s)))}else o=n&~i,o!==0?r=Di(o):s!==0&&(r=Di(s));if(r===0)return 0;if(t!==0&&t!==r&&!(t&i)&&(i=r&-r,s=t&-t,i>=s||i===16&&(s&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function gs(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Yt(t),e[t]=n}function g0(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Wi),Ic=" ",Ac=!1;function uh(e,t){switch(e){case"keyup":return H0.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function ch(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Vr=!1;function q0(e,t){switch(e){case"compositionend":return ch(t);case"keypress":return t.which!==32?null:(Ac=!0,Ic);case"textInput":return e=t.data,e===Ic&&Ac?null:e;default:return null}}function K0(e,t){if(Vr)return e==="compositionend"||!bu&&uh(e,t)?(e=ah(),Gs=_u=Xn=null,Vr=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Pc(n)}}function ph(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?ph(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function mh(){for(var e=window,t=mo();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=mo(e.document)}return t}function Eu(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function ng(e){var t=mh(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&ph(n.ownerDocument.documentElement,n)){if(r!==null&&Eu(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var i=n.textContent.length,s=Math.min(r.start,i);r=r.end===void 0?s:Math.min(r.end,i),!e.extend&&s>r&&(i=r,r=s,s=i),i=Fc(n,s);var o=Fc(n,r);i&&o&&(e.rangeCount!==1||e.anchorNode!==i.node||e.anchorOffset!==i.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(i.node,i.offset),e.removeAllRanges(),s>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,qr=null,gl=null,Vi=null,yl=!1;function Dc(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;yl||qr==null||qr!==mo(r)||(r=qr,"selectionStart"in r&&Eu(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Vi&&is(Vi,r)||(Vi=r,r=ko(gl,"onSelect"),0Yr||(e.current=Sl[Yr],Sl[Yr]=null,Yr--)}function Oe(e,t){Yr++,Sl[Yr]=e.current,e.current=t}var ar={},ot=ur(ar),gt=ur(!1),Er=ar;function ci(e,t){var n=e.type.contextTypes;if(!n)return ar;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var i={},s;for(s in n)i[s]=t[s];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function yt(e){return e=e.childContextTypes,e!=null}function bo(){Le(gt),Le(ot)}function Vc(e,t,n){if(ot.current!==ar)throw Error(ae(168));Oe(ot,t),Oe(gt,n)}function bh(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var i in r)if(!(i in t))throw Error(ae(108,Qm(e)||"Unknown",i));return Ue({},n,r)}function Eo(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||ar,Er=ot.current,Oe(ot,e),Oe(gt,gt.current),!0}function qc(e,t,n){var r=e.stateNode;if(!r)throw Error(ae(169));n?(e=bh(e,t,Er),r.__reactInternalMemoizedMergedChildContext=e,Le(gt),Le(ot),Oe(ot,e)):Le(gt),Oe(gt,n)}var Cn=null,Xo=!1,Oa=!1;function Eh(e){Cn===null?Cn=[e]:Cn.push(e)}function pg(e){Xo=!0,Eh(e)}function cr(){if(!Oa&&Cn!==null){Oa=!0;var e=0,t=Re;try{var n=Cn;for(Re=1;e>=o,i-=o,Rn=1<<32-Yt(t)+i|n<P?(O=T,T=null):O=T.sibling;var M=x(c,T,w[P],k);if(M===null){T===null&&(T=O);break}e&&T&&M.alternate===null&&t(c,T),h=s(M,h,P),N===null?b=M:N.sibling=M,N=M,T=O}if(P===w.length)return n(c,T),Fe&&mr(c,P),b;if(T===null){for(;PP?(O=T,T=null):O=T.sibling;var J=x(c,T,M.value,k);if(J===null){T===null&&(T=O);break}e&&T&&J.alternate===null&&t(c,T),h=s(J,h,P),N===null?b=J:N.sibling=J,N=J,T=O}if(M.done)return n(c,T),Fe&&mr(c,P),b;if(T===null){for(;!M.done;P++,M=w.next())M=y(c,M.value,k),M!==null&&(h=s(M,h,P),N===null?b=M:N.sibling=M,N=M);return Fe&&mr(c,P),b}for(T=r(c,T);!M.done;P++,M=w.next())M=g(T,c,P,M.value,k),M!==null&&(e&&M.alternate!==null&&T.delete(M.key===null?P:M.key),h=s(M,h,P),N===null?b=M:N.sibling=M,N=M);return e&&T.forEach(function(R){return t(c,R)}),Fe&&mr(c,P),b}function v(c,h,w,k){if(typeof w=="object"&&w!==null&&w.type===Hr&&w.key===null&&(w=w.props.children),typeof w=="object"&&w!==null){switch(w.$$typeof){case Ns:e:{for(var b=w.key,N=h;N!==null;){if(N.key===b){if(b=w.type,b===Hr){if(N.tag===7){n(c,N.sibling),h=i(N,w.props.children),h.return=c,c=h;break e}}else if(N.elementType===b||typeof b=="object"&&b!==null&&b.$$typeof===Wn&&Yc(b)===N.type){n(c,N.sibling),h=i(N,w.props),h.ref=Ii(c,N,w),h.return=c,c=h;break e}n(c,N);break}else t(c,N);N=N.sibling}w.type===Hr?(h=Sr(w.props.children,c.mode,k,w.key),h.return=c,c=h):(k=oo(w.type,w.key,w.props,null,c.mode,k),k.ref=Ii(c,h,w),k.return=c,c=k)}return o(c);case Wr:e:{for(N=w.key;h!==null;){if(h.key===N)if(h.tag===4&&h.stateNode.containerInfo===w.containerInfo&&h.stateNode.implementation===w.implementation){n(c,h.sibling),h=i(h,w.children||[]),h.return=c,c=h;break e}else{n(c,h);break}else t(c,h);h=h.sibling}h=Da(w,c.mode,k),h.return=c,c=h}return o(c);case Wn:return N=w._init,v(c,h,N(w._payload),k)}if(Fi(w))return m(c,h,w,k);if(Ci(w))return u(c,h,w,k);Ds(c,w)}return typeof w=="string"&&w!==""||typeof w=="number"?(w=""+w,h!==null&&h.tag===6?(n(c,h.sibling),h=i(h,w),h.return=c,c=h):(n(c,h),h=Fa(w,c.mode,k),h.return=c,c=h),o(c)):n(c,h)}return v}var fi=Th(!0),Oh=Th(!1),Ro=ur(null),To=null,Gr=null,Tu=null;function Ou(){Tu=Gr=To=null}function Iu(e){var t=Ro.current;Le(Ro),e._currentValue=t}function Cl(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function oi(e,t){To=e,Tu=Gr=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(mt=!0),e.firstContext=null)}function Bt(e){var t=e._currentValue;if(Tu!==e)if(e={context:e,memoizedValue:t,next:null},Gr===null){if(To===null)throw Error(ae(308));Gr=e,To.dependencies={lanes:0,firstContext:e}}else Gr=Gr.next=e;return t}var wr=null;function Au(e){wr===null?wr=[e]:wr.push(e)}function Ih(e,t,n,r){var i=t.interleaved;return i===null?(n.next=n,Au(t)):(n.next=i.next,i.next=n),t.interleaved=n,jn(e,r)}function jn(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Hn=!1;function ju(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Ah(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function On(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function er(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Ce&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,jn(e,n)}return i=r.interleaved,i===null?(t.next=t,Au(r)):(t.next=i.next,i.next=t),r.interleaved=t,jn(e,n)}function eo(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,vu(e,n)}}function Zc(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,s=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};s===null?i=s=o:s=s.next=o,n=n.next}while(n!==null);s===null?i=s=t:s=s.next=t}else i=s=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:s,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Oo(e,t,n,r){var i=e.updateQueue;Hn=!1;var s=i.firstBaseUpdate,o=i.lastBaseUpdate,a=i.shared.pending;if(a!==null){i.shared.pending=null;var l=a,d=l.next;l.next=null,o===null?s=d:o.next=d,o=l;var p=e.alternate;p!==null&&(p=p.updateQueue,a=p.lastBaseUpdate,a!==o&&(a===null?p.firstBaseUpdate=d:a.next=d,p.lastBaseUpdate=l))}if(s!==null){var y=i.baseState;o=0,p=d=l=null,a=s;do{var x=a.lane,g=a.eventTime;if((r&x)===x){p!==null&&(p=p.next={eventTime:g,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var m=e,u=a;switch(x=t,g=n,u.tag){case 1:if(m=u.payload,typeof m=="function"){y=m.call(g,y,x);break e}y=m;break e;case 3:m.flags=m.flags&-65537|128;case 0:if(m=u.payload,x=typeof m=="function"?m.call(g,y,x):m,x==null)break e;y=Ue({},y,x);break e;case 2:Hn=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,x=i.effects,x===null?i.effects=[a]:x.push(a))}else g={eventTime:g,lane:x,tag:a.tag,payload:a.payload,callback:a.callback,next:null},p===null?(d=p=g,l=y):p=p.next=g,o|=x;if(a=a.next,a===null){if(a=i.shared.pending,a===null)break;x=a,a=x.next,x.next=null,i.lastBaseUpdate=x,i.shared.pending=null}}while(!0);if(p===null&&(l=y),i.baseState=l,i.firstBaseUpdate=d,i.lastBaseUpdate=p,t=i.shared.interleaved,t!==null){i=t;do o|=i.lane,i=i.next;while(i!==t)}else s===null&&(i.shared.lanes=0);Rr|=o,e.lanes=o,e.memoizedState=y}}function Qc(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Aa.transition;Aa.transition={};try{e(!1),t()}finally{Re=n,Aa.transition=r}}function Yh(){return Ut().memoizedState}function vg(e,t,n){var r=nr(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Zh(e))Qh(t,n);else if(n=Ih(e,t,n,r),n!==null){var i=dt();Zt(n,e,r,i),Gh(n,t,r)}}function wg(e,t,n){var r=nr(e),i={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Zh(e))Qh(t,i);else{var s=e.alternate;if(e.lanes===0&&(s===null||s.lanes===0)&&(s=t.lastRenderedReducer,s!==null))try{var o=t.lastRenderedState,a=s(o,n);if(i.hasEagerState=!0,i.eagerState=a,Qt(a,o)){var l=t.interleaved;l===null?(i.next=i,Au(t)):(i.next=l.next,l.next=i),t.interleaved=i;return}}catch{}finally{}n=Ih(e,t,i,r),n!==null&&(i=dt(),Zt(n,e,r,i),Gh(n,t,r))}}function Zh(e){var t=e.alternate;return e===Be||t!==null&&t===Be}function Qh(e,t){qi=Ao=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Gh(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,vu(e,n)}}var jo={readContext:Bt,useCallback:nt,useContext:nt,useEffect:nt,useImperativeHandle:nt,useInsertionEffect:nt,useLayoutEffect:nt,useMemo:nt,useReducer:nt,useRef:nt,useState:nt,useDebugValue:nt,useDeferredValue:nt,useTransition:nt,useMutableSource:nt,useSyncExternalStore:nt,useId:nt,unstable_isNewReconciler:!1},xg={readContext:Bt,useCallback:function(e,t){return ln().memoizedState=[e,t===void 0?null:t],e},useContext:Bt,useEffect:Jc,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,no(4194308,4,Hh.bind(null,t,e),n)},useLayoutEffect:function(e,t){return no(4194308,4,e,t)},useInsertionEffect:function(e,t){return no(4,2,e,t)},useMemo:function(e,t){var n=ln();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ln();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=vg.bind(null,Be,e),[r.memoizedState,e]},useRef:function(e){var t=ln();return e={current:e},t.memoizedState=e},useState:Gc,useDebugValue:Uu,useDeferredValue:function(e){return ln().memoizedState=e},useTransition:function(){var e=Gc(!1),t=e[0];return e=yg.bind(null,e[1]),ln().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Be,i=ln();if(Fe){if(n===void 0)throw Error(ae(407));n=n()}else{if(n=t(),Qe===null)throw Error(ae(349));Nr&30||Ph(r,t,n)}i.memoizedState=n;var s={value:n,getSnapshot:t};return i.queue=s,Jc(Dh.bind(null,r,s,e),[e]),r.flags|=2048,fs(9,Fh.bind(null,r,s,n,t),void 0,null),n},useId:function(){var e=ln(),t=Qe.identifierPrefix;if(Fe){var n=Tn,r=Rn;n=(r&~(1<<32-Yt(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=cs++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(n,{is:r.is}):(e=o.createElement(n),n==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,n),e[un]=t,e[as]=r,lp(e,t,!1,!1),t.stateNode=e;e:{switch(o=ll(n,r),n){case"dialog":ze("cancel",e),ze("close",e),i=r;break;case"iframe":case"object":case"embed":ze("load",e),i=r;break;case"video":case"audio":for(i=0;imi&&(t.flags|=128,r=!0,Ai(s,!1),t.lanes=4194304)}else{if(!r)if(e=Io(o),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Ai(s,!0),s.tail===null&&s.tailMode==="hidden"&&!o.alternate&&!Fe)return rt(t),null}else 2*He()-s.renderingStartTime>mi&&n!==1073741824&&(t.flags|=128,r=!0,Ai(s,!1),t.lanes=4194304);s.isBackwards?(o.sibling=t.child,t.child=o):(n=s.last,n!==null?n.sibling=o:t.child=o,s.last=o)}return s.tail!==null?(t=s.tail,s.rendering=t,s.tail=t.sibling,s.renderingStartTime=He(),t.sibling=null,n=De.current,Oe(De,r?n&1|2:n&1),t):(rt(t),null);case 22:case 23:return Ku(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?St&1073741824&&(rt(t),t.subtreeFlags&6&&(t.flags|=8192)):rt(t),null;case 24:return null;case 25:return null}throw Error(ae(156,t.tag))}function Rg(e,t){switch(Nu(t),t.tag){case 1:return yt(t.type)&&bo(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return hi(),Le(gt),Le(ot),Pu(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Lu(t),null;case 13:if(Le(De),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ae(340));di()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Le(De),null;case 4:return hi(),null;case 10:return Iu(t.type._context),null;case 22:case 23:return Ku(),null;case 24:return null;default:return null}}var Bs=!1,it=!1,Tg=typeof WeakSet=="function"?WeakSet:Set,he=null;function Jr(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){$e(e,t,r)}else n.current=null}function Ll(e,t,n){try{n()}catch(r){$e(e,t,r)}}var cd=!1;function Og(e,t){if(vl=xo,e=mh(),Eu(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var i=r.anchorOffset,s=r.focusNode;r=r.focusOffset;try{n.nodeType,s.nodeType}catch{n=null;break e}var o=0,a=-1,l=-1,d=0,p=0,y=e,x=null;t:for(;;){for(var g;y!==n||i!==0&&y.nodeType!==3||(a=o+i),y!==s||r!==0&&y.nodeType!==3||(l=o+r),y.nodeType===3&&(o+=y.nodeValue.length),(g=y.firstChild)!==null;)x=y,y=g;for(;;){if(y===e)break t;if(x===n&&++d===i&&(a=o),x===s&&++p===r&&(l=o),(g=y.nextSibling)!==null)break;y=x,x=y.parentNode}y=g}n=a===-1||l===-1?null:{start:a,end:l}}else n=null}n=n||{start:0,end:0}}else n=null;for(wl={focusedElem:e,selectionRange:n},xo=!1,he=t;he!==null;)if(t=he,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,he=e;else for(;he!==null;){t=he;try{var m=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(m!==null){var u=m.memoizedProps,v=m.memoizedState,c=t.stateNode,h=c.getSnapshotBeforeUpdate(t.elementType===t.type?u:Vt(t.type,u),v);c.__reactInternalSnapshotBeforeUpdate=h}break;case 3:var w=t.stateNode.containerInfo;w.nodeType===1?w.textContent="":w.nodeType===9&&w.documentElement&&w.removeChild(w.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ae(163))}}catch(k){$e(t,t.return,k)}if(e=t.sibling,e!==null){e.return=t.return,he=e;break}he=t.return}return m=cd,cd=!1,m}function Ki(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var i=r=r.next;do{if((i.tag&e)===e){var s=i.destroy;i.destroy=void 0,s!==void 0&&Ll(t,n,s)}i=i.next}while(i!==r)}}function Qo(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Pl(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function dp(e){var t=e.alternate;t!==null&&(e.alternate=null,dp(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[un],delete t[as],delete t[kl],delete t[fg],delete t[hg])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function fp(e){return e.tag===5||e.tag===3||e.tag===4}function dd(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||fp(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Fl(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=So));else if(r!==4&&(e=e.child,e!==null))for(Fl(e,t,n),e=e.sibling;e!==null;)Fl(e,t,n),e=e.sibling}function Dl(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Dl(e,t,n),e=e.sibling;e!==null;)Dl(e,t,n),e=e.sibling}var Ge=null,qt=!1;function $n(e,t,n){for(n=n.child;n!==null;)hp(e,t,n),n=n.sibling}function hp(e,t,n){if(cn&&typeof cn.onCommitFiberUnmount=="function")try{cn.onCommitFiberUnmount(Wo,n)}catch{}switch(n.tag){case 5:it||Jr(n,t);case 6:var r=Ge,i=qt;Ge=null,$n(e,t,n),Ge=r,qt=i,Ge!==null&&(qt?(e=Ge,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Ge.removeChild(n.stateNode));break;case 18:Ge!==null&&(qt?(e=Ge,n=n.stateNode,e.nodeType===8?Ta(e.parentNode,n):e.nodeType===1&&Ta(e,n),ns(e)):Ta(Ge,n.stateNode));break;case 4:r=Ge,i=qt,Ge=n.stateNode.containerInfo,qt=!0,$n(e,t,n),Ge=r,qt=i;break;case 0:case 11:case 14:case 15:if(!it&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){i=r=r.next;do{var s=i,o=s.destroy;s=s.tag,o!==void 0&&(s&2||s&4)&&Ll(n,t,o),i=i.next}while(i!==r)}$n(e,t,n);break;case 1:if(!it&&(Jr(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){$e(n,t,a)}$n(e,t,n);break;case 21:$n(e,t,n);break;case 22:n.mode&1?(it=(r=it)||n.memoizedState!==null,$n(e,t,n),it=r):$n(e,t,n);break;default:$n(e,t,n)}}function fd(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Tg),t.forEach(function(r){var i=Mg.bind(null,e,r);n.has(r)||(n.add(r),r.then(i,i))})}}function Ht(e,t){var n=t.deletions;if(n!==null)for(var r=0;ri&&(i=o),r&=~s}if(r=i,r=He()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Ag(r/1960))-r,10e?16:e,Yn===null)var r=!1;else{if(e=Yn,Yn=null,Po=0,Ce&6)throw Error(ae(331));var i=Ce;for(Ce|=4,he=e.current;he!==null;){var s=he,o=s.child;if(he.flags&16){var a=s.deletions;if(a!==null){for(var l=0;lHe()-Vu?kr(e,0):Hu|=n),vt(e,t)}function _p(e,t){t===0&&(e.mode&1?(t=Is,Is<<=1,!(Is&130023424)&&(Is=4194304)):t=1);var n=dt();e=jn(e,t),e!==null&&(gs(e,t,n),vt(e,n))}function Dg(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),_p(e,n)}function Mg(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,i=e.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ae(314))}r!==null&&r.delete(t),_p(e,n)}var kp;kp=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||gt.current)mt=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return mt=!1,Cg(e,t,n);mt=!!(e.flags&131072)}else mt=!1,Fe&&t.flags&1048576&&Ch(t,No,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;ro(e,t),e=t.pendingProps;var i=ci(t,ot.current);oi(t,n),i=Du(null,t,r,e,i,n);var s=Mu();return t.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,yt(r)?(s=!0,Eo(t)):s=!1,t.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,ju(t),i.updater=Zo,t.stateNode=i,i._reactInternals=t,Rl(t,r,e,n),t=Il(null,t,r,!0,s,n)):(t.tag=0,Fe&&s&&Cu(t),ct(null,t,i,n),t=t.child),t;case 16:r=t.elementType;e:{switch(ro(e,t),e=t.pendingProps,i=r._init,r=i(r._payload),t.type=r,i=t.tag=Ug(r),e=Vt(r,e),i){case 0:t=Ol(null,t,r,e,n);break e;case 1:t=ad(null,t,r,e,n);break e;case 11:t=sd(null,t,r,e,n);break e;case 14:t=od(null,t,r,Vt(r.type,e),n);break e}throw Error(ae(306,r,""))}return t;case 0:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Vt(r,i),Ol(e,t,r,i,n);case 1:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Vt(r,i),ad(e,t,r,i,n);case 3:e:{if(sp(t),e===null)throw Error(ae(387));r=t.pendingProps,s=t.memoizedState,i=s.element,Ah(e,t),Oo(t,r,null,n);var o=t.memoizedState;if(r=o.element,s.isDehydrated)if(s={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=s,t.memoizedState=s,t.flags&256){i=pi(Error(ae(423)),t),t=ld(e,t,r,n,i);break e}else if(r!==i){i=pi(Error(ae(424)),t),t=ld(e,t,r,n,i);break e}else for(bt=Jn(t.stateNode.containerInfo.firstChild),Et=t,Fe=!0,Xt=null,n=Oh(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(di(),r===i){t=zn(e,t,n);break e}ct(e,t,r,n)}t=t.child}return t;case 5:return jh(t),e===null&&El(t),r=t.type,i=t.pendingProps,s=e!==null?e.memoizedProps:null,o=i.children,xl(r,i)?o=null:s!==null&&xl(r,s)&&(t.flags|=32),ip(e,t),ct(e,t,o,n),t.child;case 6:return e===null&&El(t),null;case 13:return op(e,t,n);case 4:return zu(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=fi(t,null,r,n):ct(e,t,r,n),t.child;case 11:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Vt(r,i),sd(e,t,r,i,n);case 7:return ct(e,t,t.pendingProps,n),t.child;case 8:return ct(e,t,t.pendingProps.children,n),t.child;case 12:return ct(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,i=t.pendingProps,s=t.memoizedProps,o=i.value,Oe(Ro,r._currentValue),r._currentValue=o,s!==null)if(Qt(s.value,o)){if(s.children===i.children&&!gt.current){t=zn(e,t,n);break e}}else for(s=t.child,s!==null&&(s.return=t);s!==null;){var a=s.dependencies;if(a!==null){o=s.child;for(var l=a.firstContext;l!==null;){if(l.context===r){if(s.tag===1){l=On(-1,n&-n),l.tag=2;var d=s.updateQueue;if(d!==null){d=d.shared;var p=d.pending;p===null?l.next=l:(l.next=p.next,p.next=l),d.pending=l}}s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),Cl(s.return,n,t),a.lanes|=n;break}l=l.next}}else if(s.tag===10)o=s.type===t.type?null:s.child;else if(s.tag===18){if(o=s.return,o===null)throw Error(ae(341));o.lanes|=n,a=o.alternate,a!==null&&(a.lanes|=n),Cl(o,n,t),o=s.sibling}else o=s.child;if(o!==null)o.return=s;else for(o=s;o!==null;){if(o===t){o=null;break}if(s=o.sibling,s!==null){s.return=o.return,o=s;break}o=o.return}s=o}ct(e,t,i.children,n),t=t.child}return t;case 9:return i=t.type,r=t.pendingProps.children,oi(t,n),i=Bt(i),r=r(i),t.flags|=1,ct(e,t,r,n),t.child;case 14:return r=t.type,i=Vt(r,t.pendingProps),i=Vt(r.type,i),od(e,t,r,i,n);case 15:return np(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Vt(r,i),ro(e,t),t.tag=1,yt(r)?(e=!0,Eo(t)):e=!1,oi(t,n),Jh(t,r,i),Rl(t,r,i,n),Il(null,t,r,!0,e,n);case 19:return ap(e,t,n);case 22:return rp(e,t,n)}throw Error(ae(156,t.tag))};function Sp(e,t){return Zf(e,t)}function Bg(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Dt(e,t,n,r){return new Bg(e,t,n,r)}function Yu(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Ug(e){if(typeof e=="function")return Yu(e)?1:0;if(e!=null){if(e=e.$$typeof,e===pu)return 11;if(e===mu)return 14}return 2}function rr(e,t){var n=e.alternate;return n===null?(n=Dt(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function oo(e,t,n,r,i,s){var o=2;if(r=e,typeof e=="function")Yu(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case Hr:return Sr(n.children,i,s,t);case hu:o=8,i|=8;break;case Ga:return e=Dt(12,n,t,i|2),e.elementType=Ga,e.lanes=s,e;case Ja:return e=Dt(13,n,t,i),e.elementType=Ja,e.lanes=s,e;case el:return e=Dt(19,n,t,i),e.elementType=el,e.lanes=s,e;case jf:return Jo(n,i,s,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case If:o=10;break e;case Af:o=9;break e;case pu:o=11;break e;case mu:o=14;break e;case Wn:o=16,r=null;break e}throw Error(ae(130,e==null?e:typeof e,""))}return t=Dt(o,n,t,i),t.elementType=e,t.type=r,t.lanes=s,t}function Sr(e,t,n,r){return e=Dt(7,e,r,t),e.lanes=n,e}function Jo(e,t,n,r){return e=Dt(22,e,r,t),e.elementType=jf,e.lanes=n,e.stateNode={isHidden:!1},e}function Fa(e,t,n){return e=Dt(6,e,null,t),e.lanes=n,e}function Da(e,t,n){return t=Dt(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function $g(e,t,n,r,i){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=va(0),this.expirationTimes=va(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=va(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function Zu(e,t,n,r,i,s,o,a,l){return e=new $g(e,t,n,a,l),t===1?(t=1,s===!0&&(t|=8)):t=0,s=Dt(3,null,null,t),e.current=s,s.stateNode=e,s.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},ju(s),e}function Wg(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Np)}catch(e){console.error(e)}}Np(),Nf.exports=Nt;var Rp=Nf.exports,xd=Rp;Za.createRoot=xd.createRoot,Za.hydrateRoot=xd.hydrateRoot;const hn=Object.create(null);hn.open="0";hn.close="1";hn.ping="2";hn.pong="3";hn.message="4";hn.upgrade="5";hn.noop="6";const ao=Object.create(null);Object.keys(hn).forEach(e=>{ao[hn[e]]=e});const Wl={type:"error",data:"parser error"},Tp=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Op=typeof ArrayBuffer=="function",Ip=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ec=({type:e,data:t},n,r)=>Tp&&t instanceof Blob?n?r(t):_d(t,r):Op&&(t instanceof ArrayBuffer||Ip(t))?n?r(t):_d(new Blob([t]),r):r(hn[e]+(t||"")),_d=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function kd(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Ma;function Xg(e,t){if(Tp&&e.data instanceof Blob)return e.data.arrayBuffer().then(kd).then(t);if(Op&&(e.data instanceof ArrayBuffer||Ip(e.data)))return t(kd(e.data));ec(e,!1,n=>{Ma||(Ma=new TextEncoder),t(Ma.encode(n))})}const Sd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Bi=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,i=0,s,o,a,l;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const d=new ArrayBuffer(t),p=new Uint8Array(d);for(r=0;r>4,p[i++]=(o&15)<<4|a>>2,p[i++]=(a&3)<<6|l&63;return d},Zg=typeof ArrayBuffer=="function",tc=(e,t)=>{if(typeof e!="string")return{type:"message",data:Ap(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:Qg(e.substring(1),t)}:ao[n]?e.length>1?{type:ao[n],data:e.substring(1)}:{type:ao[n]}:Wl},Qg=(e,t)=>{if(Zg){const n=Yg(e);return Ap(n,t)}else return{base64:!0,data:e}},Ap=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},jp="",Gg=(e,t)=>{const n=e.length,r=new Array(n);let i=0;e.forEach((s,o)=>{ec(s,!1,a=>{r[o]=a,++i===n&&t(r.join(jp))})})},Jg=(e,t)=>{const n=e.split(jp),r=[];for(let i=0;i{const r=n.length;let i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);const s=new DataView(i.buffer);s.setUint8(0,126),s.setUint16(1,r)}else{i=new Uint8Array(9);const s=new DataView(i.buffer);s.setUint8(0,127),s.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}})}let Ba;function Ws(e){return e.reduce((t,n)=>t+n.length,0)}function Hs(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let i=0;iMath.pow(2,21)-1){a.enqueue(Wl);break}i=p*Math.pow(2,32)+d.getUint32(4),r=3}else{if(Ws(n)e){a.enqueue(Wl);break}}}})}const zp=4;function qe(e){if(e)return ny(e)}function ny(e){for(var t in qe.prototype)e[t]=qe.prototype[t];return e}qe.prototype.on=qe.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};qe.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};qe.prototype.off=qe.prototype.removeListener=qe.prototype.removeAllListeners=qe.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var r,i=0;iPromise.resolve().then(t):(t,n)=>n(t,0),Pt=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),ry="arraybuffer";function Lp(e,...t){return t.reduce((n,r)=>(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const iy=Pt.setTimeout,sy=Pt.clearTimeout;function sa(e,t){t.useNativeTimers?(e.setTimeoutFn=iy.bind(Pt),e.clearTimeoutFn=sy.bind(Pt)):(e.setTimeoutFn=Pt.setTimeout.bind(Pt),e.clearTimeoutFn=Pt.clearTimeout.bind(Pt))}const oy=1.33;function ay(e){return typeof e=="string"?ly(e):Math.ceil((e.byteLength||e.size)*oy)}function ly(e){let t=0,n=0;for(let r=0,i=e.length;r=57344?n+=3:(r++,n+=4);return n}function Pp(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function uy(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function cy(e){let t={},n=e.split("&");for(let r=0,i=n.length;r{this.readyState="paused",t()};if(this._polling||!this.writable){let r=0;this._polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};Jg(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,Gg(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=Pp()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}}let Fp=!1;try{Fp=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const hy=Fp;function py(){}class my extends fy{constructor(t){if(super(t),typeof location<"u"){const n=location.protocol==="https:";let r=location.port;r||(r=n?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||r!==t.port}}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(i,s)=>{this.onError("xhr post error",i,s)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=t}}class fn extends qe{constructor(t,n,r){super(),this.createRequest=t,sa(this,r),this._opts=r,this._method=r.method||"GET",this._uri=n,this._data=r.data!==void 0?r.data:null,this._create()}_create(){var t;const n=Lp(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this._opts.xd;const r=this._xhr=this.createRequest(n);try{r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&r.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(r),"withCredentials"in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var i;r.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(r.getResponseHeader("set-cookie"))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status=="number"?r.status:0)},0))},r.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=fn.requestsCount++,fn.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=py,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete fn.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}fn.requestsCount=0;fn.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",bd);else if(typeof addEventListener=="function"){const e="onpagehide"in Pt?"pagehide":"unload";addEventListener(e,bd,!1)}}function bd(){for(let e in fn.requests)fn.requests.hasOwnProperty(e)&&fn.requests[e].abort()}const gy=function(){const e=Dp({xdomain:!1});return e&&e.responseType!==null}();class yy extends my{constructor(t){super(t);const n=t&&t.forceBase64;this.supportsBinary=gy&&!n}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new fn(Dp,this.uri(),t)}}function Dp(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||hy))return new XMLHttpRequest}catch{}if(!t)try{return new Pt[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Mp=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class vy extends nc{get name(){return"websocket"}doOpen(){const t=this.uri(),n=this.opts.protocols,r=Mp?{}:Lp(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,n,r)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n{try{this.doWrite(r,s)}catch{}i&&ia(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=Pp()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}}const Ua=Pt.WebSocket||Pt.MozWebSocket;class wy extends vy{createSocket(t,n,r){return Mp?new Ua(t,n,r):n?new Ua(t,n):new Ua(t)}doWrite(t,n){this.ws.send(n)}}class xy extends nc{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const n=ty(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),i=ey();i.readable.pipeTo(t.writable),this._writer=i.writable.getWriter();const s=()=>{r.read().then(({done:a,value:l})=>{a||(this.onPacket(l),s())}).catch(a=>{})};s();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let n=0;n{i&&ia(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const _y={websocket:wy,webtransport:xy,polling:yy},ky=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Sy=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Hl(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let i=ky.exec(e||""),s={},o=14;for(;o--;)s[Sy[o]]=i[o]||"";return n!=-1&&r!=-1&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=by(s,s.path),s.queryKey=Ey(s,s.query),s}function by(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&r.splice(0,1),t.slice(-1)=="/"&&r.splice(r.length-1,1),r}function Ey(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,i,s){i&&(n[i]=s)}),n}const Vl=typeof addEventListener=="function"&&typeof removeEventListener=="function",lo=[];Vl&&addEventListener("offline",()=>{lo.forEach(e=>e())},!1);class ir extends qe{constructor(t,n){if(super(),this.binaryType=ry,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(n=t,t=null),t){const r=Hl(t);n.hostname=r.host,n.secure=r.protocol==="https"||r.protocol==="wss",n.port=r.port,r.query&&(n.query=r.query)}else n.host&&(n.hostname=Hl(n.host).host);sa(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},n.transports.forEach(r=>{const i=r.prototype.name;this.transports.push(i),this._transportsByName[i]=r}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=cy(this.opts.query)),Vl&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},lo.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=zp,n.transport=t,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](r)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&ir.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",n=>this._onClose("transport close",n))}onOpen(){this.readyState="open",ir.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const n=new Error("server error");n.code=t.data,this._onError(n);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r0&&n>this._maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,ia(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,n,r){return this._sendPacket("message",t,n,r),this}send(t,n,r){return this._sendPacket("message",t,n,r),this}_sendPacket(t,n,r,i){if(typeof n=="function"&&(i=n,n=void 0),typeof r=="function"&&(i=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const s={type:t,data:n,options:r};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),i&&this.once("flush",i),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():t()}):this.upgrading?r():t()),this}_onError(t){if(ir.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,n){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Vl&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const r=lo.indexOf(this._offlineEventListener);r!==-1&&lo.splice(r,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this._prevBufferLen=0}}}ir.protocol=zp;class Cy extends ir{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",y=>{if(!r)if(y.type==="pong"&&y.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;ir.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(p(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const x=new Error("probe error");x.transport=n.name,this.emitReserved("upgradeError",x)}}))};function s(){r||(r=!0,p(),n.close(),n=null)}const o=y=>{const x=new Error("probe error: "+y);x.transport=n.name,s(),this.emitReserved("upgradeError",x)};function a(){o("transport closed")}function l(){o("socket closed")}function d(y){n&&y.name!==n.name&&s()}const p=()=>{n.removeListener("open",i),n.removeListener("error",o),n.removeListener("close",a),this.off("close",l),this.off("upgrading",d)};n.once("open",i),n.once("error",o),n.once("close",a),this.once("close",l),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const n=[];for(let r=0;r_y[i]).filter(i=>!!i)),super(t,r)}};function Ry(e,t="",n){let r=e;n=n||typeof location<"u"&&location,e==null&&(e=n.protocol+"//"+n.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=n.protocol+e:e=n.host+e),/^(https?|wss?):\/\//.test(e)||(typeof n<"u"?e=n.protocol+"//"+e:e="https://"+e),r=Hl(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const s=r.host.indexOf(":")!==-1?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+s+":"+r.port+t,r.href=r.protocol+"://"+s+(n&&n.port===r.port?"":":"+r.port),r}const Ty=typeof ArrayBuffer=="function",Oy=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,Bp=Object.prototype.toString,Iy=typeof Blob=="function"||typeof Blob<"u"&&Bp.call(Blob)==="[object BlobConstructor]",Ay=typeof File=="function"||typeof File<"u"&&Bp.call(File)==="[object FileConstructor]";function rc(e){return Ty&&(e instanceof ArrayBuffer||Oy(e))||Iy&&e instanceof Blob||Ay&&e instanceof File}function uo(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n=0&&e.num{delete this.acks[t];for(let a=0;a{this.io.clearTimeoutFn(s),n.apply(this,a)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...n){return new Promise((r,i)=>{const s=(o,a)=>o?i(o):r(a);s.withError=!0,n.push(s),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((i,...s)=>r!==this._queue[0]?void 0:(i!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(i)):(this._queue.shift(),n&&n(null,...s)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:Ee.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(r=>String(r.id)===t)){const r=this.acks[t];delete this.acks[t],r.withError&&r.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case Ee.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Ee.EVENT:case Ee.BINARY_EVENT:this.onevent(t);break;case Ee.ACK:case Ee.BINARY_ACK:this.onack(t);break;case Ee.DISCONNECT:this.ondisconnect();break;case Ee.CONNECT_ERROR:this.destroy();const r=new Error(t.data.message);r.data=t.data.data,this.emitReserved("connect_error",r);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let r=!1;return function(...i){r||(r=!0,n.packet({type:Ee.ACK,id:t,data:i}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(delete this.acks[t.id],n.withError&&t.data.unshift(null),n.apply(this,t.data))}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Ee.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let r=0;r0&&e.jitter<=1?e.jitter:0,this.attempts=0}_i.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0};_i.prototype.reset=function(){this.attempts=0};_i.prototype.setMin=function(e){this.ms=e};_i.prototype.setMax=function(e){this.max=e};_i.prototype.setJitter=function(e){this.jitter=e};class Xl extends qe{constructor(t,n){var r;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,sa(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new _i({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const i=n.parser||My;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new Ny(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=Kt(n,"open",function(){r.onopen(),t&&t()}),s=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),t?t(a):this.maybeReconnectOnOpen()},o=Kt(n,"error",s);if(this._timeout!==!1){const a=this._timeout,l=this.setTimeoutFn(()=>{i(),s(new Error("timeout")),n.close()},a);this.opts.autoUnref&&l.unref(),this.subs.push(()=>{this.clearTimeoutFn(l)})}return this.subs.push(i),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(Kt(t,"ping",this.onping.bind(this)),Kt(t,"data",this.ondata.bind(this)),Kt(t,"error",this.onerror.bind(this)),Kt(t,"close",this.onclose.bind(this)),Kt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){ia(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let r=this.nsps[t];return r?this._autoConnect&&!r.active&&r.connect():(r=new Up(this,t,n),this.nsps[t]=r),r}_destroy(t){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let r=0;rt()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,n){var r;this.cleanup(),(r=this.engine)===null||r===void 0||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(i=>{i?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",i)):t.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const zi={};function co(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=Ry(e,t.path||"/socket.io"),r=n.source,i=n.id,s=n.path,o=zi[i]&&s in zi[i].nsps,a=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let l;return a?l=new Xl(r,t):(zi[i]||(zi[i]=new Xl(r,t)),l=zi[i]),n.query&&!t.query&&(t.query=n.queryKey),l.socket(n.path,t)}Object.assign(co,{Manager:Xl,Socket:Up,io:co,connect:co});const Uy={},Cd=e=>{let t;const n=new Set,r=(p,y)=>{const x=typeof p=="function"?p(t):p;if(!Object.is(x,t)){const g=t;t=y??(typeof x!="object"||x===null)?x:Object.assign({},t,x),n.forEach(m=>m(t,g))}},i=()=>t,l={setState:r,getState:i,getInitialState:()=>d,subscribe:p=>(n.add(p),()=>n.delete(p)),destroy:()=>{(Uy?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},d=t=e(r,i,l);return l},$y=e=>e?Cd(e):Cd;var $p={exports:{}},Wp={},Hp={exports:{}},Vp={};/** - * @license React - * use-sync-external-store-shim.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var gi=Z;function Wy(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Hy=typeof Object.is=="function"?Object.is:Wy,Vy=gi.useState,qy=gi.useEffect,Ky=gi.useLayoutEffect,Xy=gi.useDebugValue;function Yy(e,t){var n=t(),r=Vy({inst:{value:n,getSnapshot:t}}),i=r[0].inst,s=r[1];return Ky(function(){i.value=n,i.getSnapshot=t,$a(i)&&s({inst:i})},[e,n,t]),qy(function(){return $a(i)&&s({inst:i}),e(function(){$a(i)&&s({inst:i})})},[e]),Xy(n),n}function $a(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Hy(e,n)}catch{return!0}}function Zy(e,t){return t()}var Qy=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Zy:Yy;Vp.useSyncExternalStore=gi.useSyncExternalStore!==void 0?gi.useSyncExternalStore:Qy;Hp.exports=Vp;var Gy=Hp.exports;/** - * @license React - * use-sync-external-store-shim/with-selector.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var oa=Z,Jy=Gy;function ev(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var tv=typeof Object.is=="function"?Object.is:ev,nv=Jy.useSyncExternalStore,rv=oa.useRef,iv=oa.useEffect,sv=oa.useMemo,ov=oa.useDebugValue;Wp.useSyncExternalStoreWithSelector=function(e,t,n,r,i){var s=rv(null);if(s.current===null){var o={hasValue:!1,value:null};s.current=o}else o=s.current;s=sv(function(){function l(g){if(!d){if(d=!0,p=g,g=r(g),i!==void 0&&o.hasValue){var m=o.value;if(i(m,g))return y=m}return y=g}if(m=y,tv(p,g))return m;var u=r(g);return i!==void 0&&i(m,u)?(p=g,m):(p=g,y=u)}var d=!1,p,y,x=n===void 0?null:n;return[function(){return l(t())},x===null?void 0:function(){return l(x())}]},[t,n,r,i]);var a=nv(e,s[0],s[1]);return iv(function(){o.hasValue=!0,o.value=a},[a]),ov(a),a};$p.exports=Wp;var av=$p.exports;const lv=su(av),qp={},{useDebugValue:uv}=ke,{useSyncExternalStoreWithSelector:cv}=lv;let Nd=!1;const dv=e=>e;function fv(e,t=dv,n){(qp?"production":void 0)!=="production"&&n&&!Nd&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),Nd=!0);const r=cv(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return uv(r),r}const Rd=e=>{(qp?"production":void 0)!=="production"&&typeof e!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const t=typeof e=="function"?$y(e):e,n=(r,i)=>fv(t,r,i);return Object.assign(n,t),n},hv=e=>e?Rd(e):Rd,me=hv((e,t)=>({theme:"light",setTheme:n=>e({theme:n}),toggleTheme:()=>e(n=>({theme:n.theme==="light"?"dark":"light"})),libraries:[],currentLibraryId:null,setLibraries:n=>e({libraries:n}),setCurrentLibrary:n=>e({currentLibraryId:n}),addLibrary:n=>e(r=>({libraries:[...r.libraries,n]})),removeLibrary:n=>e(r=>({libraries:r.libraries.filter(i=>i.id!==n),currentLibraryId:r.currentLibraryId===n?null:r.currentLibraryId})),images:[],filteredImages:[],totalImageCount:0,setImages:n=>e({images:n,filteredImages:n}),setFilteredImages:n=>e({filteredImages:n}),setTotalImageCount:n=>e({totalImageCount:n}),imageLoadingState:{isLoading:!1,loadedCount:0,totalCount:0,hasMore:!1},setImageLoadingState:n=>e(r=>({imageLoadingState:{...r.imageLoadingState,...n}})),appendImages:n=>e(r=>({images:[...r.images,...n],filteredImages:[...r.filteredImages,...n]})),folders:[],selectedFolder:null,setFolders:n=>e({folders:n}),setSelectedFolder:n=>e({selectedFolder:n}),searchKeywords:"",filters:{formats:[],minSize:null,maxSize:null,startDate:null,endDate:null},setSearchKeywords:n=>e({searchKeywords:n}),setFilters:n=>e(r=>({filters:{...r.filters,...n}})),resetFilters:()=>e({searchKeywords:"",filters:{formats:[],minSize:null,maxSize:null,startDate:null,endDate:null}}),selectedImage:null,setSelectedImage:n=>e({selectedImage:n}),selectedImages:[],setSelectedImages:n=>e({selectedImages:n}),toggleImageSelection:n=>e(r=>r.selectedImages.some(s=>s.path===n.path)?{selectedImages:r.selectedImages.filter(s=>s.path!==n.path)}:{selectedImages:[...r.selectedImages,n]}),clearSelection:()=>e({selectedImages:[],selectedImage:null}),scanProgress:null,scanStartTime:null,setScanProgress:n=>e(r=>n&&!r.scanStartTime&&n.current>0?{scanProgress:n,scanStartTime:Date.now()}:n?{scanProgress:n}:{scanProgress:null,scanStartTime:null}),isResizingPanels:!1,setIsResizingPanels:n=>e({isResizingPanels:n}),resizingSide:null,setResizingSide:n=>e({resizingSide:n}),thumbnailHeight:200,setThumbnailHeight:n=>e({thumbnailHeight:n}),mobileView:"main",setMobileView:n=>e({mobileView:n}),getCurrentLibrary:()=>{const n=t();return n.libraries.find(r=>r.id===n.currentLibraryId)}}));function Kp(e,t){return function(){return e.apply(t,arguments)}}const{toString:pv}=Object.prototype,{getPrototypeOf:sc}=Object,{iterator:aa,toStringTag:Xp}=Symbol,la=(e=>t=>{const n=pv.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Gt=e=>(e=e.toLowerCase(),t=>la(t)===e),ua=e=>t=>typeof t===e,{isArray:ki}=Array,yi=ua("undefined");function xs(e){return e!==null&&!yi(e)&&e.constructor!==null&&!yi(e.constructor)&&wt(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Yp=Gt("ArrayBuffer");function mv(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Yp(e.buffer),t}const gv=ua("string"),wt=ua("function"),Zp=ua("number"),_s=e=>e!==null&&typeof e=="object",yv=e=>e===!0||e===!1,fo=e=>{if(la(e)!=="object")return!1;const t=sc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Xp in e)&&!(aa in e)},vv=e=>{if(!_s(e)||xs(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},wv=Gt("Date"),xv=Gt("File"),_v=Gt("Blob"),kv=Gt("FileList"),Sv=e=>_s(e)&&wt(e.pipe),bv=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||wt(e.append)&&((t=la(e))==="formdata"||t==="object"&&wt(e.toString)&&e.toString()==="[object FormData]"))},Ev=Gt("URLSearchParams"),[Cv,Nv,Rv,Tv]=["ReadableStream","Request","Response","Headers"].map(Gt),Ov=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function ks(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,i;if(typeof e!="object"&&(e=[e]),ki(e))for(r=0,i=e.length;r0;)if(i=n[r],t===i.toLowerCase())return i;return null}const _r=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Gp=e=>!yi(e)&&e!==_r;function Yl(){const{caseless:e,skipUndefined:t}=Gp(this)&&this||{},n={},r=(i,s)=>{const o=e&&Qp(n,s)||s;fo(n[o])&&fo(i)?n[o]=Yl(n[o],i):fo(i)?n[o]=Yl({},i):ki(i)?n[o]=i.slice():(!t||!yi(i))&&(n[o]=i)};for(let i=0,s=arguments.length;i(ks(t,(i,s)=>{n&&wt(i)?e[s]=Kp(i,n):e[s]=i},{allOwnKeys:r}),e),Av=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),jv=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},zv=(e,t,n,r)=>{let i,s,o;const a={};if(t=t||{},e==null)return t;do{for(i=Object.getOwnPropertyNames(e),s=i.length;s-- >0;)o=i[s],(!r||r(o,e,t))&&!a[o]&&(t[o]=e[o],a[o]=!0);e=n!==!1&&sc(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},Lv=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},Pv=e=>{if(!e)return null;if(ki(e))return e;let t=e.length;if(!Zp(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},Fv=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&sc(Uint8Array)),Dv=(e,t)=>{const r=(e&&e[aa]).call(e);let i;for(;(i=r.next())&&!i.done;){const s=i.value;t.call(e,s[0],s[1])}},Mv=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},Bv=Gt("HTMLFormElement"),Uv=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,i){return r.toUpperCase()+i}),Td=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),$v=Gt("RegExp"),Jp=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};ks(n,(i,s)=>{let o;(o=t(i,s,e))!==!1&&(r[s]=o||i)}),Object.defineProperties(e,r)},Wv=e=>{Jp(e,(t,n)=>{if(wt(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(wt(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},Hv=(e,t)=>{const n={},r=i=>{i.forEach(s=>{n[s]=!0})};return ki(e)?r(e):r(String(e).split(t)),n},Vv=()=>{},qv=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function Kv(e){return!!(e&&wt(e.append)&&e[Xp]==="FormData"&&e[aa])}const Xv=e=>{const t=new Array(10),n=(r,i)=>{if(_s(r)){if(t.indexOf(r)>=0)return;if(xs(r))return r;if(!("toJSON"in r)){t[i]=r;const s=ki(r)?[]:{};return ks(r,(o,a)=>{const l=n(o,i+1);!yi(l)&&(s[a]=l)}),t[i]=void 0,s}}return r};return n(e,0)},Yv=Gt("AsyncFunction"),Zv=e=>e&&(_s(e)||wt(e))&&wt(e.then)&&wt(e.catch),em=((e,t)=>e?setImmediate:t?((n,r)=>(_r.addEventListener("message",({source:i,data:s})=>{i===_r&&s===n&&r.length&&r.shift()()},!1),i=>{r.push(i),_r.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",wt(_r.postMessage)),Qv=typeof queueMicrotask<"u"?queueMicrotask.bind(_r):typeof process<"u"&&process.nextTick||em,Gv=e=>e!=null&&wt(e[aa]),K={isArray:ki,isArrayBuffer:Yp,isBuffer:xs,isFormData:bv,isArrayBufferView:mv,isString:gv,isNumber:Zp,isBoolean:yv,isObject:_s,isPlainObject:fo,isEmptyObject:vv,isReadableStream:Cv,isRequest:Nv,isResponse:Rv,isHeaders:Tv,isUndefined:yi,isDate:wv,isFile:xv,isBlob:_v,isRegExp:$v,isFunction:wt,isStream:Sv,isURLSearchParams:Ev,isTypedArray:Fv,isFileList:kv,forEach:ks,merge:Yl,extend:Iv,trim:Ov,stripBOM:Av,inherits:jv,toFlatObject:zv,kindOf:la,kindOfTest:Gt,endsWith:Lv,toArray:Pv,forEachEntry:Dv,matchAll:Mv,isHTMLForm:Bv,hasOwnProperty:Td,hasOwnProp:Td,reduceDescriptors:Jp,freezeMethods:Wv,toObjectSet:Hv,toCamelCase:Uv,noop:Vv,toFiniteNumber:qv,findKey:Qp,global:_r,isContextDefined:Gp,isSpecCompliantForm:Kv,toJSONObject:Xv,isAsyncFn:Yv,isThenable:Zv,setImmediate:em,asap:Qv,isIterable:Gv};function we(e,t,n,r,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),i&&(this.response=i,this.status=i.status?i.status:null)}K.inherits(we,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:K.toJSONObject(this.config),code:this.code,status:this.status}}});const tm=we.prototype,nm={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{nm[e]={value:e}});Object.defineProperties(we,nm);Object.defineProperty(tm,"isAxiosError",{value:!0});we.from=(e,t,n,r,i,s)=>{const o=Object.create(tm);K.toFlatObject(e,o,function(p){return p!==Error.prototype},d=>d!=="isAxiosError");const a=e&&e.message?e.message:"Error",l=t==null&&e?e.code:t;return we.call(o,a,l,n,r,i),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",s&&Object.assign(o,s),o};const Jv=null;function Zl(e){return K.isPlainObject(e)||K.isArray(e)}function rm(e){return K.endsWith(e,"[]")?e.slice(0,-2):e}function Od(e,t,n){return e?e.concat(t).map(function(i,s){return i=rm(i),!n&&s?"["+i+"]":i}).join(n?".":""):t}function e1(e){return K.isArray(e)&&!e.some(Zl)}const t1=K.toFlatObject(K,{},null,function(t){return/^is[A-Z]/.test(t)});function ca(e,t,n){if(!K.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=K.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(u,v){return!K.isUndefined(v[u])});const r=n.metaTokens,i=n.visitor||p,s=n.dots,o=n.indexes,l=(n.Blob||typeof Blob<"u"&&Blob)&&K.isSpecCompliantForm(t);if(!K.isFunction(i))throw new TypeError("visitor must be a function");function d(m){if(m===null)return"";if(K.isDate(m))return m.toISOString();if(K.isBoolean(m))return m.toString();if(!l&&K.isBlob(m))throw new we("Blob is not supported. Use a Buffer instead.");return K.isArrayBuffer(m)||K.isTypedArray(m)?l&&typeof Blob=="function"?new Blob([m]):Buffer.from(m):m}function p(m,u,v){let c=m;if(m&&!v&&typeof m=="object"){if(K.endsWith(u,"{}"))u=r?u:u.slice(0,-2),m=JSON.stringify(m);else if(K.isArray(m)&&e1(m)||(K.isFileList(m)||K.endsWith(u,"[]"))&&(c=K.toArray(m)))return u=rm(u),c.forEach(function(w,k){!(K.isUndefined(w)||w===null)&&t.append(o===!0?Od([u],k,s):o===null?u:u+"[]",d(w))}),!1}return Zl(m)?!0:(t.append(Od(v,u,s),d(m)),!1)}const y=[],x=Object.assign(t1,{defaultVisitor:p,convertValue:d,isVisitable:Zl});function g(m,u){if(!K.isUndefined(m)){if(y.indexOf(m)!==-1)throw Error("Circular reference detected in "+u.join("."));y.push(m),K.forEach(m,function(c,h){(!(K.isUndefined(c)||c===null)&&i.call(t,c,K.isString(h)?h.trim():h,u,x))===!0&&g(c,u?u.concat(h):[h])}),y.pop()}}if(!K.isObject(e))throw new TypeError("data must be an object");return g(e),t}function Id(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function oc(e,t){this._pairs=[],e&&ca(e,this,t)}const im=oc.prototype;im.append=function(t,n){this._pairs.push([t,n])};im.toString=function(t){const n=t?function(r){return t.call(this,r,Id)}:Id;return this._pairs.map(function(i){return n(i[0])+"="+n(i[1])},"").join("&")};function n1(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function sm(e,t,n){if(!t)return e;const r=n&&n.encode||n1;K.isFunction(n)&&(n={serialize:n});const i=n&&n.serialize;let s;if(i?s=i(t,n):s=K.isURLSearchParams(t)?t.toString():new oc(t,n).toString(r),s){const o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+s}return e}class Ad{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){K.forEach(this.handlers,function(r){r!==null&&t(r)})}}const om={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},r1=typeof URLSearchParams<"u"?URLSearchParams:oc,i1=typeof FormData<"u"?FormData:null,s1=typeof Blob<"u"?Blob:null,o1={isBrowser:!0,classes:{URLSearchParams:r1,FormData:i1,Blob:s1},protocols:["http","https","file","blob","url","data"]},ac=typeof window<"u"&&typeof document<"u",Ql=typeof navigator=="object"&&navigator||void 0,a1=ac&&(!Ql||["ReactNative","NativeScript","NS"].indexOf(Ql.product)<0),l1=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",u1=ac&&window.location.href||"http://localhost",c1=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:ac,hasStandardBrowserEnv:a1,hasStandardBrowserWebWorkerEnv:l1,navigator:Ql,origin:u1},Symbol.toStringTag,{value:"Module"})),st={...c1,...o1};function d1(e,t){return ca(e,new st.classes.URLSearchParams,{visitor:function(n,r,i,s){return st.isNode&&K.isBuffer(n)?(this.append(r,n.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)},...t})}function f1(e){return K.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function h1(e){const t={},n=Object.keys(e);let r;const i=n.length;let s;for(r=0;r=n.length;return o=!o&&K.isArray(i)?i.length:o,l?(K.hasOwnProp(i,o)?i[o]=[i[o],r]:i[o]=r,!a):((!i[o]||!K.isObject(i[o]))&&(i[o]=[]),t(n,r,i[o],s)&&K.isArray(i[o])&&(i[o]=h1(i[o])),!a)}if(K.isFormData(e)&&K.isFunction(e.entries)){const n={};return K.forEachEntry(e,(r,i)=>{t(f1(r),i,n,0)}),n}return null}function p1(e,t,n){if(K.isString(e))try{return(t||JSON.parse)(e),K.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const Ss={transitional:om,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",i=r.indexOf("application/json")>-1,s=K.isObject(t);if(s&&K.isHTMLForm(t)&&(t=new FormData(t)),K.isFormData(t))return i?JSON.stringify(am(t)):t;if(K.isArrayBuffer(t)||K.isBuffer(t)||K.isStream(t)||K.isFile(t)||K.isBlob(t)||K.isReadableStream(t))return t;if(K.isArrayBufferView(t))return t.buffer;if(K.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let a;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return d1(t,this.formSerializer).toString();if((a=K.isFileList(t))||r.indexOf("multipart/form-data")>-1){const l=this.env&&this.env.FormData;return ca(a?{"files[]":t}:t,l&&new l,this.formSerializer)}}return s||i?(n.setContentType("application/json",!1),p1(t)):t}],transformResponse:[function(t){const n=this.transitional||Ss.transitional,r=n&&n.forcedJSONParsing,i=this.responseType==="json";if(K.isResponse(t)||K.isReadableStream(t))return t;if(t&&K.isString(t)&&(r&&!this.responseType||i)){const o=!(n&&n.silentJSONParsing)&&i;try{return JSON.parse(t,this.parseReviver)}catch(a){if(o)throw a.name==="SyntaxError"?we.from(a,we.ERR_BAD_RESPONSE,this,null,this.response):a}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:st.classes.FormData,Blob:st.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};K.forEach(["delete","get","head","post","put","patch"],e=>{Ss.headers[e]={}});const m1=K.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),g1=e=>{const t={};let n,r,i;return e&&e.split(` -`).forEach(function(o){i=o.indexOf(":"),n=o.substring(0,i).trim().toLowerCase(),r=o.substring(i+1).trim(),!(!n||t[n]&&m1[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},jd=Symbol("internals");function Li(e){return e&&String(e).trim().toLowerCase()}function ho(e){return e===!1||e==null?e:K.isArray(e)?e.map(ho):String(e)}function y1(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const v1=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Wa(e,t,n,r,i){if(K.isFunction(r))return r.call(this,t,n);if(i&&(t=n),!!K.isString(t)){if(K.isString(r))return t.indexOf(r)!==-1;if(K.isRegExp(r))return r.test(t)}}function w1(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function x1(e,t){const n=K.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(i,s,o){return this[r].call(this,t,i,s,o)},configurable:!0})})}let xt=class{constructor(t){t&&this.set(t)}set(t,n,r){const i=this;function s(a,l,d){const p=Li(l);if(!p)throw new Error("header name must be a non-empty string");const y=K.findKey(i,p);(!y||i[y]===void 0||d===!0||d===void 0&&i[y]!==!1)&&(i[y||l]=ho(a))}const o=(a,l)=>K.forEach(a,(d,p)=>s(d,p,l));if(K.isPlainObject(t)||t instanceof this.constructor)o(t,n);else if(K.isString(t)&&(t=t.trim())&&!v1(t))o(g1(t),n);else if(K.isObject(t)&&K.isIterable(t)){let a={},l,d;for(const p of t){if(!K.isArray(p))throw TypeError("Object iterator must return a key-value pair");a[d=p[0]]=(l=a[d])?K.isArray(l)?[...l,p[1]]:[l,p[1]]:p[1]}o(a,n)}else t!=null&&s(n,t,r);return this}get(t,n){if(t=Li(t),t){const r=K.findKey(this,t);if(r){const i=this[r];if(!n)return i;if(n===!0)return y1(i);if(K.isFunction(n))return n.call(this,i,r);if(K.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=Li(t),t){const r=K.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||Wa(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let i=!1;function s(o){if(o=Li(o),o){const a=K.findKey(r,o);a&&(!n||Wa(r,r[a],a,n))&&(delete r[a],i=!0)}}return K.isArray(t)?t.forEach(s):s(t),i}clear(t){const n=Object.keys(this);let r=n.length,i=!1;for(;r--;){const s=n[r];(!t||Wa(this,this[s],s,t,!0))&&(delete this[s],i=!0)}return i}normalize(t){const n=this,r={};return K.forEach(this,(i,s)=>{const o=K.findKey(r,s);if(o){n[o]=ho(i),delete n[s];return}const a=t?w1(s):String(s).trim();a!==s&&delete n[s],n[a]=ho(i),r[a]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return K.forEach(this,(r,i)=>{r!=null&&r!==!1&&(n[i]=t&&K.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` -`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(i=>r.set(i)),r}static accessor(t){const r=(this[jd]=this[jd]={accessors:{}}).accessors,i=this.prototype;function s(o){const a=Li(o);r[a]||(x1(i,o),r[a]=!0)}return K.isArray(t)?t.forEach(s):s(t),this}};xt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);K.reduceDescriptors(xt.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});K.freezeMethods(xt);function Ha(e,t){const n=this||Ss,r=t||n,i=xt.from(r.headers);let s=r.data;return K.forEach(e,function(a){s=a.call(n,s,i.normalize(),t?t.status:void 0)}),i.normalize(),s}function lm(e){return!!(e&&e.__CANCEL__)}function Si(e,t,n){we.call(this,e??"canceled",we.ERR_CANCELED,t,n),this.name="CanceledError"}K.inherits(Si,we,{__CANCEL__:!0});function um(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new we("Request failed with status code "+n.status,[we.ERR_BAD_REQUEST,we.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function _1(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function k1(e,t){e=e||10;const n=new Array(e),r=new Array(e);let i=0,s=0,o;return t=t!==void 0?t:1e3,function(l){const d=Date.now(),p=r[s];o||(o=d),n[i]=l,r[i]=d;let y=s,x=0;for(;y!==i;)x+=n[y++],y=y%e;if(i=(i+1)%e,i===s&&(s=(s+1)%e),d-o{n=p,i=null,s&&(clearTimeout(s),s=null),e(...d)};return[(...d)=>{const p=Date.now(),y=p-n;y>=r?o(d,p):(i=d,s||(s=setTimeout(()=>{s=null,o(i)},r-y)))},()=>i&&o(i)]}const Mo=(e,t,n=3)=>{let r=0;const i=k1(50,250);return S1(s=>{const o=s.loaded,a=s.lengthComputable?s.total:void 0,l=o-r,d=i(l),p=o<=a;r=o;const y={loaded:o,total:a,progress:a?o/a:void 0,bytes:l,rate:d||void 0,estimated:d&&a&&p?(a-o)/d:void 0,event:s,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(y)},n)},zd=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Ld=e=>(...t)=>K.asap(()=>e(...t)),b1=st.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,st.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(st.origin),st.navigator&&/(msie|trident)/i.test(st.navigator.userAgent)):()=>!0,E1=st.hasStandardBrowserEnv?{write(e,t,n,r,i,s,o){if(typeof document>"u")return;const a=[`${e}=${encodeURIComponent(t)}`];K.isNumber(n)&&a.push(`expires=${new Date(n).toUTCString()}`),K.isString(r)&&a.push(`path=${r}`),K.isString(i)&&a.push(`domain=${i}`),s===!0&&a.push("secure"),K.isString(o)&&a.push(`SameSite=${o}`),document.cookie=a.join("; ")},read(e){if(typeof document>"u")return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function C1(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function N1(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function cm(e,t,n){let r=!C1(t);return e&&(r||n==!1)?N1(e,t):t}const Pd=e=>e instanceof xt?{...e}:e;function Or(e,t){t=t||{};const n={};function r(d,p,y,x){return K.isPlainObject(d)&&K.isPlainObject(p)?K.merge.call({caseless:x},d,p):K.isPlainObject(p)?K.merge({},p):K.isArray(p)?p.slice():p}function i(d,p,y,x){if(K.isUndefined(p)){if(!K.isUndefined(d))return r(void 0,d,y,x)}else return r(d,p,y,x)}function s(d,p){if(!K.isUndefined(p))return r(void 0,p)}function o(d,p){if(K.isUndefined(p)){if(!K.isUndefined(d))return r(void 0,d)}else return r(void 0,p)}function a(d,p,y){if(y in t)return r(d,p);if(y in e)return r(void 0,d)}const l={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(d,p,y)=>i(Pd(d),Pd(p),y,!0)};return K.forEach(Object.keys({...e,...t}),function(p){const y=l[p]||i,x=y(e[p],t[p],p);K.isUndefined(x)&&y!==a||(n[p]=x)}),n}const dm=e=>{const t=Or({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:i,xsrfCookieName:s,headers:o,auth:a}=t;if(t.headers=o=xt.from(o),t.url=sm(cm(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&o.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),K.isFormData(n)){if(st.hasStandardBrowserEnv||st.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(K.isFunction(n.getHeaders)){const l=n.getHeaders(),d=["content-type","content-length"];Object.entries(l).forEach(([p,y])=>{d.includes(p.toLowerCase())&&o.set(p,y)})}}if(st.hasStandardBrowserEnv&&(r&&K.isFunction(r)&&(r=r(t)),r||r!==!1&&b1(t.url))){const l=i&&s&&E1.read(s);l&&o.set(i,l)}return t},R1=typeof XMLHttpRequest<"u",T1=R1&&function(e){return new Promise(function(n,r){const i=dm(e);let s=i.data;const o=xt.from(i.headers).normalize();let{responseType:a,onUploadProgress:l,onDownloadProgress:d}=i,p,y,x,g,m;function u(){g&&g(),m&&m(),i.cancelToken&&i.cancelToken.unsubscribe(p),i.signal&&i.signal.removeEventListener("abort",p)}let v=new XMLHttpRequest;v.open(i.method.toUpperCase(),i.url,!0),v.timeout=i.timeout;function c(){if(!v)return;const w=xt.from("getAllResponseHeaders"in v&&v.getAllResponseHeaders()),b={data:!a||a==="text"||a==="json"?v.responseText:v.response,status:v.status,statusText:v.statusText,headers:w,config:e,request:v};um(function(T){n(T),u()},function(T){r(T),u()},b),v=null}"onloadend"in v?v.onloadend=c:v.onreadystatechange=function(){!v||v.readyState!==4||v.status===0&&!(v.responseURL&&v.responseURL.indexOf("file:")===0)||setTimeout(c)},v.onabort=function(){v&&(r(new we("Request aborted",we.ECONNABORTED,e,v)),v=null)},v.onerror=function(k){const b=k&&k.message?k.message:"Network Error",N=new we(b,we.ERR_NETWORK,e,v);N.event=k||null,r(N),v=null},v.ontimeout=function(){let k=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const b=i.transitional||om;i.timeoutErrorMessage&&(k=i.timeoutErrorMessage),r(new we(k,b.clarifyTimeoutError?we.ETIMEDOUT:we.ECONNABORTED,e,v)),v=null},s===void 0&&o.setContentType(null),"setRequestHeader"in v&&K.forEach(o.toJSON(),function(k,b){v.setRequestHeader(b,k)}),K.isUndefined(i.withCredentials)||(v.withCredentials=!!i.withCredentials),a&&a!=="json"&&(v.responseType=i.responseType),d&&([x,m]=Mo(d,!0),v.addEventListener("progress",x)),l&&v.upload&&([y,g]=Mo(l),v.upload.addEventListener("progress",y),v.upload.addEventListener("loadend",g)),(i.cancelToken||i.signal)&&(p=w=>{v&&(r(!w||w.type?new Si(null,e,v):w),v.abort(),v=null)},i.cancelToken&&i.cancelToken.subscribe(p),i.signal&&(i.signal.aborted?p():i.signal.addEventListener("abort",p)));const h=_1(i.url);if(h&&st.protocols.indexOf(h)===-1){r(new we("Unsupported protocol "+h+":",we.ERR_BAD_REQUEST,e));return}v.send(s||null)})},O1=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,i;const s=function(d){if(!i){i=!0,a();const p=d instanceof Error?d:this.reason;r.abort(p instanceof we?p:new Si(p instanceof Error?p.message:p))}};let o=t&&setTimeout(()=>{o=null,s(new we(`timeout ${t} of ms exceeded`,we.ETIMEDOUT))},t);const a=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(d=>{d.unsubscribe?d.unsubscribe(s):d.removeEventListener("abort",s)}),e=null)};e.forEach(d=>d.addEventListener("abort",s));const{signal:l}=r;return l.unsubscribe=()=>K.asap(a),l}},I1=function*(e,t){let n=e.byteLength;if(n{const i=A1(e,t);let s=0,o,a=l=>{o||(o=!0,r&&r(l))};return new ReadableStream({async pull(l){try{const{done:d,value:p}=await i.next();if(d){a(),l.close();return}let y=p.byteLength;if(n){let x=s+=y;n(x)}l.enqueue(new Uint8Array(p))}catch(d){throw a(d),d}},cancel(l){return a(l),i.return()}},{highWaterMark:2})},Dd=64*1024,{isFunction:Vs}=K,z1=(({Request:e,Response:t})=>({Request:e,Response:t}))(K.global),{ReadableStream:Md,TextEncoder:Bd}=K.global,Ud=(e,...t)=>{try{return!!e(...t)}catch{return!1}},L1=e=>{e=K.merge.call({skipUndefined:!0},z1,e);const{fetch:t,Request:n,Response:r}=e,i=t?Vs(t):typeof fetch=="function",s=Vs(n),o=Vs(r);if(!i)return!1;const a=i&&Vs(Md),l=i&&(typeof Bd=="function"?(m=>u=>m.encode(u))(new Bd):async m=>new Uint8Array(await new n(m).arrayBuffer())),d=s&&a&&Ud(()=>{let m=!1;const u=new n(st.origin,{body:new Md,method:"POST",get duplex(){return m=!0,"half"}}).headers.has("Content-Type");return m&&!u}),p=o&&a&&Ud(()=>K.isReadableStream(new r("").body)),y={stream:p&&(m=>m.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(m=>{!y[m]&&(y[m]=(u,v)=>{let c=u&&u[m];if(c)return c.call(u);throw new we(`Response type '${m}' is not supported`,we.ERR_NOT_SUPPORT,v)})});const x=async m=>{if(m==null)return 0;if(K.isBlob(m))return m.size;if(K.isSpecCompliantForm(m))return(await new n(st.origin,{method:"POST",body:m}).arrayBuffer()).byteLength;if(K.isArrayBufferView(m)||K.isArrayBuffer(m))return m.byteLength;if(K.isURLSearchParams(m)&&(m=m+""),K.isString(m))return(await l(m)).byteLength},g=async(m,u)=>{const v=K.toFiniteNumber(m.getContentLength());return v??x(u)};return async m=>{let{url:u,method:v,data:c,signal:h,cancelToken:w,timeout:k,onDownloadProgress:b,onUploadProgress:N,responseType:T,headers:P,withCredentials:O="same-origin",fetchOptions:M}=dm(m),J=t||fetch;T=T?(T+"").toLowerCase():"text";let R=O1([h,w&&w.toAbortSignal()],k),W=null;const _=R&&R.unsubscribe&&(()=>{R.unsubscribe()});let V;try{if(N&&d&&v!=="get"&&v!=="head"&&(V=await g(P,c))!==0){let z=new n(u,{method:"POST",body:c,duplex:"half"}),F;if(K.isFormData(c)&&(F=z.headers.get("content-type"))&&P.setContentType(F),z.body){const[A,B]=zd(V,Mo(Ld(N)));c=Fd(z.body,Dd,A,B)}}K.isString(O)||(O=O?"include":"omit");const ce=s&&"credentials"in n.prototype,Q={...M,signal:R,method:v.toUpperCase(),headers:P.normalize().toJSON(),body:c,duplex:"half",credentials:ce?O:void 0};W=s&&new n(u,Q);let H=await(s?J(W,M):J(u,Q));const U=p&&(T==="stream"||T==="response");if(p&&(b||U&&_)){const z={};["status","statusText","headers"].forEach(D=>{z[D]=H[D]});const F=K.toFiniteNumber(H.headers.get("content-length")),[A,B]=b&&zd(F,Mo(Ld(b),!0))||[];H=new r(Fd(H.body,Dd,A,()=>{B&&B(),_&&_()}),z)}T=T||"text";let ee=await y[K.findKey(y,T)||"text"](H,m);return!U&&_&&_(),await new Promise((z,F)=>{um(z,F,{data:ee,headers:xt.from(H.headers),status:H.status,statusText:H.statusText,config:m,request:W})})}catch(ce){throw _&&_(),ce&&ce.name==="TypeError"&&/Load failed|fetch/i.test(ce.message)?Object.assign(new we("Network Error",we.ERR_NETWORK,m,W),{cause:ce.cause||ce}):we.from(ce,ce&&ce.code,m,W)}}},P1=new Map,fm=e=>{let t=e&&e.env||{};const{fetch:n,Request:r,Response:i}=t,s=[r,i,n];let o=s.length,a=o,l,d,p=P1;for(;a--;)l=s[a],d=p.get(l),d===void 0&&p.set(l,d=a?new Map:L1(t)),p=d;return d};fm();const lc={http:Jv,xhr:T1,fetch:{get:fm}};K.forEach(lc,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const $d=e=>`- ${e}`,F1=e=>K.isFunction(e)||e===null||e===!1;function D1(e,t){e=K.isArray(e)?e:[e];const{length:n}=e;let r,i;const s={};for(let o=0;o`adapter ${l} `+(d===!1?"is not supported by the environment":"is not available in the build"));let a=n?o.length>1?`since : -`+o.map($d).join(` -`):" "+$d(o[0]):"as no adapter specified";throw new we("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return i}const hm={getAdapter:D1,adapters:lc};function Va(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Si(null,e)}function Wd(e){return Va(e),e.headers=xt.from(e.headers),e.data=Ha.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),hm.getAdapter(e.adapter||Ss.adapter,e)(e).then(function(r){return Va(e),r.data=Ha.call(e,e.transformResponse,r),r.headers=xt.from(r.headers),r},function(r){return lm(r)||(Va(e),r&&r.response&&(r.response.data=Ha.call(e,e.transformResponse,r.response),r.response.headers=xt.from(r.response.headers))),Promise.reject(r)})}const pm="1.13.2",da={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{da[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Hd={};da.transitional=function(t,n,r){function i(s,o){return"[Axios v"+pm+"] Transitional option '"+s+"'"+o+(r?". "+r:"")}return(s,o,a)=>{if(t===!1)throw new we(i(o," has been removed"+(n?" in "+n:"")),we.ERR_DEPRECATED);return n&&!Hd[o]&&(Hd[o]=!0,console.warn(i(o," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(s,o,a):!0}};da.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function M1(e,t,n){if(typeof e!="object")throw new we("options must be an object",we.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let i=r.length;for(;i-- >0;){const s=r[i],o=t[s];if(o){const a=e[s],l=a===void 0||o(a,s,e);if(l!==!0)throw new we("option "+s+" must be "+l,we.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new we("Unknown option "+s,we.ERR_BAD_OPTION)}}const po={assertOptions:M1,validators:da},an=po.validators;let br=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Ad,response:new Ad}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const s=i.stack?i.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=` -`+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Or(this.defaults,n);const{transitional:r,paramsSerializer:i,headers:s}=n;r!==void 0&&po.assertOptions(r,{silentJSONParsing:an.transitional(an.boolean),forcedJSONParsing:an.transitional(an.boolean),clarifyTimeoutError:an.transitional(an.boolean)},!1),i!=null&&(K.isFunction(i)?n.paramsSerializer={serialize:i}:po.assertOptions(i,{encode:an.function,serialize:an.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),po.assertOptions(n,{baseUrl:an.spelling("baseURL"),withXsrfToken:an.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let o=s&&K.merge(s.common,s[n.method]);s&&K.forEach(["delete","get","head","post","put","patch","common"],m=>{delete s[m]}),n.headers=xt.concat(o,s);const a=[];let l=!0;this.interceptors.request.forEach(function(u){typeof u.runWhen=="function"&&u.runWhen(n)===!1||(l=l&&u.synchronous,a.unshift(u.fulfilled,u.rejected))});const d=[];this.interceptors.response.forEach(function(u){d.push(u.fulfilled,u.rejected)});let p,y=0,x;if(!l){const m=[Wd.bind(this),void 0];for(m.unshift(...a),m.push(...d),x=m.length,p=Promise.resolve(n);y{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](i);r._listeners=null}),this.promise.then=i=>{let s;const o=new Promise(a=>{r.subscribe(a),s=a}).then(i);return o.cancel=function(){r.unsubscribe(s)},o},t(function(s,o,a){r.reason||(r.reason=new Si(s,o,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new mm(function(i){t=i}),cancel:t}}};function U1(e){return function(n){return e.apply(null,n)}}function $1(e){return K.isObject(e)&&e.isAxiosError===!0}const Gl={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Gl).forEach(([e,t])=>{Gl[t]=e});function gm(e){const t=new br(e),n=Kp(br.prototype.request,t);return K.extend(n,br.prototype,t,{allOwnKeys:!0}),K.extend(n,t,null,{allOwnKeys:!0}),n.create=function(i){return gm(Or(e,i))},n}const xe=gm(Ss);xe.Axios=br;xe.CanceledError=Si;xe.CancelToken=B1;xe.isCancel=lm;xe.VERSION=pm;xe.toFormData=ca;xe.AxiosError=we;xe.Cancel=xe.CanceledError;xe.all=function(t){return Promise.all(t)};xe.spread=U1;xe.isAxiosError=$1;xe.mergeConfig=Or;xe.AxiosHeaders=xt;xe.formToJSON=e=>am(K.isHTMLForm(e)?new FormData(e):e);xe.getAdapter=hm.getAdapter;xe.HttpStatusCode=Gl;xe.default=xe;const{Axios:Jw,AxiosError:ex,CanceledError:tx,isCancel:nx,CancelToken:rx,VERSION:ix,all:sx,Cancel:ox,isAxiosError:ax,spread:lx,toFormData:ux,AxiosHeaders:cx,HttpStatusCode:dx,formToJSON:fx,getAdapter:hx,mergeConfig:px}=xe,Pe="/api",Nn={getAll:()=>xe.get(`${Pe}/library`),add:(e,t)=>xe.post(`${Pe}/library`,{name:e,path:t}),update:(e,t)=>xe.put(`${Pe}/library/${e}`,t),delete:e=>xe.delete(`${Pe}/library/${e}`),setCurrent:e=>xe.post(`${Pe}/library/${e}/set-current`),updatePreferences:e=>xe.put(`${Pe}/library/preferences`,e),updateTheme:e=>xe.put(`${Pe}/library/theme`,{theme:e})},Me={search:(e,t={},n={})=>{const r=new URLSearchParams({libraryId:e,...t});return xe.get(`${Pe}/image?${r}`,n)},getCount:e=>xe.get(`${Pe}/image/count?libraryId=${e}`),getFolders:e=>xe.get(`${Pe}/image/folders?libraryId=${e}`),getCacheMeta:e=>xe.get(`${Pe}/image/cache-meta?libraryId=${e}`),getThumbnailUrl:(e,t,n)=>`${Pe}/image/thumbnail/${e}/${t}/${n}`,getOriginalUrl:(e,t)=>`${Pe}/image/original/${e}/${t}`,openInExplorer:(e,t)=>xe.post(`${Pe}/image/${e}/open-file`,{path:t})},sr={fullScan:(e,t=!1)=>xe.post(`${Pe}/scan/full`,{libraryId:e,wait:t}),sync:(e,t=!1)=>xe.post(`${Pe}/scan/sync`,{libraryId:e,wait:t}),stop:e=>xe.post(`${Pe}/scan/stop`,{libraryId:e}),resume:e=>xe.post(`${Pe}/scan/resume`,{libraryId:e}),getStatus:e=>xe.get(`${Pe}/scan/status/${e}`),fixFolders:e=>xe.post(`${Pe}/scan/fix-folders`,{libraryId:e})},Vd={start:e=>xe.post(`${Pe}/watch/start/${e}`),stop:e=>xe.post(`${Pe}/watch/stop/${e}`),status:e=>xe.get(`${Pe}/watch/status/${e}`),list:()=>xe.get(`${Pe}/watch/list`)};/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */var W1={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const H1=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().trim(),Ie=(e,t)=>{const n=Z.forwardRef(({color:r="currentColor",size:i=24,strokeWidth:s=2,absoluteStrokeWidth:o,className:a="",children:l,...d},p)=>Z.createElement("svg",{ref:p,...W1,width:i,height:i,stroke:r,strokeWidth:o?Number(s)*24/Number(i):s,className:["lucide",`lucide-${H1(e)}`,a].join(" "),...d},[...t.map(([y,x])=>Z.createElement(y,x)),...Array.isArray(l)?l:[l]]));return n.displayName=`${e}`,n};/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const V1=Ie("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const q1=Ie("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const qd=Ie("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const K1=Ie("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const X1=Ie("ChevronsDown",[["path",{d:"m7 6 5 5 5-5",key:"1lc07p"}],["path",{d:"m7 13 5 5 5-5",key:"1d48rs"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Y1=Ie("ChevronsRight",[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Z1=Ie("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Q1=Ie("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const G1=Ie("ExternalLink",[["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}],["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["line",{x1:"10",x2:"21",y1:"14",y2:"3",key:"18c3s4"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const J1=Ie("FileText",[["path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z",key:"1nnpy2"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}],["line",{x1:"16",x2:"8",y1:"13",y2:"13",key:"14keom"}],["line",{x1:"16",x2:"8",y1:"17",y2:"17",key:"17nazh"}],["line",{x1:"10",x2:"8",y1:"9",y2:"9",key:"1a5vjj"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ew=Ie("File",[["path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z",key:"1nnpy2"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Kd=Ie("Filter",[["polygon",{points:"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3",key:"1yg77f"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const tw=Ie("FolderDown",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"m15 13-3 3-3-3",key:"6j2sf0"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Zi=Ie("Folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const nw=Ie("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Xd=Ie("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const rw=Ie("Music",[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const iw=Ie("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",key:"1xcu5"}],["circle",{cx:"17.5",cy:"10.5",r:".5",key:"736e4u"}],["circle",{cx:"8.5",cy:"7.5",r:".5",key:"clrty"}],["circle",{cx:"6.5",cy:"12.5",r:".5",key:"1s4xz9"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const sw=Ie("Pause",[["rect",{width:"4",height:"16",x:"6",y:"4",key:"iffhe4"}],["rect",{width:"4",height:"16",x:"14",y:"4",key:"sjin7j"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ym=Ie("Play",[["polygon",{points:"5 3 19 12 5 21 5 3",key:"191637"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Yd=Ie("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Bo=Ie("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Zd=Ie("Sliders",[["line",{x1:"4",x2:"4",y1:"21",y2:"14",key:"1p332r"}],["line",{x1:"4",x2:"4",y1:"10",y2:"3",key:"gb41h5"}],["line",{x1:"12",x2:"12",y1:"21",y2:"12",key:"hf2csr"}],["line",{x1:"12",x2:"12",y1:"8",y2:"3",key:"1kfi7u"}],["line",{x1:"20",x2:"20",y1:"21",y2:"16",key:"1lhrwl"}],["line",{x1:"20",x2:"20",y1:"12",y2:"3",key:"16vvfq"}],["line",{x1:"2",x2:"6",y1:"14",y2:"14",key:"1uebub"}],["line",{x1:"10",x2:"14",y1:"8",y2:"8",key:"1yglbp"}],["line",{x1:"18",x2:"22",y1:"16",y2:"16",key:"1jxqpz"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Qd=Ie("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ow=Ie("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/** - * @license lucide-react v0.300.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const vm=Ie("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),ps={LIBRARY:"library",FOLDER:"folder",IMAGES:"images"};let Gd=0;const aw=()=>(Gd+=1,`req_${Date.now()}_${Gd}`);class lw{constructor(){this.activeRequests=new Map,this.requestContexts=new Map}createRequest(t){const n=aw(),r=new AbortController,i={id:n,type:t,createdAt:Date.now(),abortController:r,signal:r.signal,status:"pending",isActive:!0,cancel:()=>{if(i.isActive){i.isActive=!1,i.status="cancelled",r.abort(),this.requestContexts.delete(n);const s=this.activeRequests.get(t);s&&s.delete(n)}}};return this.requestContexts.set(n,i),this.activeRequests.has(t)||this.activeRequests.set(t,new Map),this.activeRequests.get(t).set(n,i),i}cancelAll(t){const n=this.activeRequests.get(t);if(n){for(const r of n.values())r.cancel();n.clear()}}cancelAllRequests(){for(const t of Object.values(ps))this.cancelAll(t)}isValid(t){const n=this.requestContexts.get(t);return n?n.isActive:!1}complete(t){const n=this.requestContexts.get(t);if(n&&n.isActive){n.status="completed",n.isActive=!1,this.requestContexts.delete(t);const r=this.activeRequests.get(n.type);r&&r.delete(t)}}error(t){const n=this.requestContexts.get(t);if(n&&n.isActive){n.status="error",n.isActive=!1,this.requestContexts.delete(t);const r=this.activeRequests.get(n.type);r&&r.delete(t)}}getActiveCount(t){const n=this.activeRequests.get(t);return n?n.size:0}hasActiveRequests(t){return this.getActiveCount(t)>0}}const Ft=new lw;function Jl(){Ft.cancelAll(ps.IMAGES)}function uw(e){e&&setTimeout(()=>{},300)}const cw=async e=>{try{return(await sr.getStatus(e)).data}catch{return null}};function Jd(){const{libraries:e,currentLibraryId:t,folders:n,selectedFolder:r,totalImageCount:i,setCurrentLibrary:s,setSelectedFolder:o,addLibrary:a,removeLibrary:l}=me(),[d,p]=Z.useState(!1),[y,x]=Z.useState(""),[g,m]=Z.useState(""),[u,v]=Z.useState(""),[c,h]=Z.useState(""),[w,k]=Z.useState(new Set),[b,N]=Z.useState(!1),[T,P]=Z.useState(!1),O=Z.useRef(null),M=A=>{h(A),O.current&&clearTimeout(O.current),O.current=setTimeout(()=>{v(A)},300)};Z.useEffect(()=>()=>{O.current&&clearTimeout(O.current)},[]);const J=async()=>{if(!y.trim()){alert("请输入素材库名称");return}if(!g.trim()){alert("请输入文件夹路径");return}N(!0);try{console.log("📝 添加素材库...");const A=await Nn.add(y.trim(),g.trim()),B=A.data.id,D=A.data.hasExistingIndex;if(a({id:B,name:y.trim(),path:g.trim()}),x(""),m(""),p(!1),N(!1),console.log("🔄 切换到新素材库..."),await Nn.setCurrent(B),s(B),o(null),me.getState().setImages([]),me.getState().setFolders([]),me.getState().setSelectedImage(null),me.getState().setTotalImageCount(0),me.getState().setScanProgress({libraryId:B,current:0,total:0,percent:0,status:"preparing"}),D){console.log("检测到已有索引,先加载现有数据...");try{const[le,de]=await Promise.all([Me.getFolders(B),Me.getCount(B)]);me.getState().setFolders(le.data.folders),me.getState().setTotalImageCount(de.data.count),console.log("✅ 已加载现有数据")}catch(le){console.warn("⚠️ 加载现有数据失败:",le)}}console.log("🔍 开始异步扫描..."),D?(console.log("执行增量同步,检测变化..."),sr.sync(B,!1)):(console.log("首次添加,执行全量扫描..."),sr.fullScan(B,!1)),console.log("✅ 扫描已启动,请等待进度显示...")}catch(A){console.error("❌ Error adding library:",A),alert("添加素材库失败: "+A.message),me.getState().setScanProgress(null),N(!1)}},R=async A=>{if(A!==t){P(!0);try{Jl(),Ft.cancelAllRequests(),me.getState().setScanProgress(null),me.getState().setSelectedImage(null),me.getState().setImages([]),me.getState().setFolders([]),me.getState().setImageLoadingState({isLoading:!1,loadedCount:0,totalCount:0,hasMore:!1}),o(null),await Nn.setCurrent(A);const[B,D]=await Promise.all([Me.getFolders(A),Me.getCount(A)]);me.getState().setFolders(B.data.folders),me.getState().setTotalImageCount(D.data.count),s(A),cw(A).then(le=>{var de,ue;le&&le.status==="paused"&&(le.needsRescan?(me.getState().setScanProgress({...le.progress,libraryId:A,canStop:!0,isPaused:!0,pendingCount:((de=le.progress)==null?void 0:de.total)-((ue=le.progress)==null?void 0:ue.current)||0,needsRescan:!0}),console.log("⏸️ 发现中断的扫描,需要继续完成")):le.pendingCount>0&&(me.getState().setScanProgress({...le.progress,libraryId:A,canStop:!0,isPaused:!0,pendingCount:le.pendingCount}),console.log(`⏸️ 发现暂停的扫描,待处理: ${le.pendingCount} 张`)))}).catch(()=>{})}catch(B){console.error("Error setting current library:",B),alert("切换素材库失败: "+B.message),me.getState().setImageLoadingState({isLoading:!1})}finally{P(!1)}}},W=async()=>{if(!t)return;const A=e.find(D=>D.id===t);if(!(!A||!confirm(`确定要删除素材库"${A.name}"吗? - -路径: ${A.path} - -⚠️ 注意: -• 将删除索引数据并释放数据库连接 -• 不会删除原始图片文件 -• .flypic 文件夹将保留,您可以手动删除`)))try{await Nn.delete(t),l(t),me.getState().setImages([]),me.getState().setFolders([]),me.getState().setSelectedImage(null),me.getState().setSelectedFolder(null);const D=e.filter(le=>le.id!==t);if(D.length>0){const le=D[0];await Nn.setCurrent(le.id),s(le.id)}console.log(`✅ 素材库已删除: ${A.name}`),console.log(`数据库连接已释放,可手动删除: ${A.path}\\.flypic`)}catch(D){console.error("Error deleting library:",D),alert("删除素材库失败: "+D.message)}},_=A=>{const B=new Set(w);B.has(A)?B.delete(A):B.add(A),k(B)},V=A=>{const B=[],D=le=>{le.forEach(de=>{de.children&&de.children.length>0&&(B.push(de.path),D(de.children))})};return D(A),B},ce=()=>{const A=V(U.length>0?U:n);k(new Set(A))},Q=()=>{k(new Set)},H=()=>{const A=V(U.length>0?U:n);return A.length>0&&A.every(B=>w.has(B))},U=Z.useMemo(()=>{if(!u)return n;const A=u.trim().toLowerCase().split(/\s+/).filter(de=>de.length>0);if(A.length===0)return n;const B=[],D=de=>de.reduce((ue,se)=>{const X=se.name.toLowerCase(),re=se.path.toLowerCase(),q=A.every(I=>X.includes(I)),ne=A.every(I=>re.includes(I));let f=[];return se.children&&se.children.length>0&&(f=D(se.children)),(q||ne||f.length>0)&&(ue.push({...se,children:f}),f.length>0&&B.push(se.path)),ue},[]),le=D(n);return B.length>0&&setTimeout(()=>{k(de=>{const ue=new Set(de);return B.forEach(se=>ue.add(se)),ue})},0),le},[n,u]),ee=(A,B)=>{A.stopPropagation(),_(B)},z=A=>{const B=A.children&&A.children.length>0;r!==A.path?(Jl(),o(A.path)):B&&_(A.path)},F=(A,B=0)=>A.map(D=>{const le=w.has(D.path),de=D.children&&D.children.length>0,ue=r===D.path;return S.jsxs("div",{children:[S.jsxs("div",{className:`flex items-center px-3 py-2 cursor-pointer rounded-md transition-colors ${ue?"bg-blue-50 dark:bg-blue-900":"hover:bg-gray-100 dark:hover:bg-gray-700"}`,style:{paddingLeft:`${B*16+12}px`},onClick:()=>z(D),children:[de?S.jsx("div",{className:"flex items-center justify-center w-5 h-5 mr-1 cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 rounded",onClick:se=>ee(se,D.path),children:le?S.jsx(qd,{className:"w-4 h-4 text-gray-500"}):S.jsx(K1,{className:"w-4 h-4 text-gray-500"})}):S.jsx("div",{className:"w-5 mr-1"}),S.jsx(Zi,{className:"w-4 h-4 mr-2 text-gray-500 flex-shrink-0"}),S.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300 truncate flex-1",children:D.name}),S.jsx("span",{className:"text-xs text-gray-400 ml-2 flex-shrink-0",children:D.image_count})]}),de&&le&&F(D.children,B+1)]},D.path)});return S.jsxs("div",{className:"w-full h-full border-r border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 flex flex-col",children:[S.jsxs("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700",children:[S.jsx("div",{className:"flex items-center justify-between mb-3",children:S.jsx("h2",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300",children:"素材库"})}),S.jsxs("div",{className:"flex gap-2",children:[S.jsxs("div",{className:"relative flex-1",children:[S.jsxs("select",{value:t||"",onChange:A=>{const B=A.target.value;B==="__add__"?p(!0):B&&R(B)},disabled:T,className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 appearance-none cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",style:{paddingRight:"2rem"},children:[e.length===0&&S.jsx("option",{value:"",children:"暂无素材库"}),e.map(A=>S.jsx("option",{value:A.id,children:A.name},A.id)),S.jsx("option",{value:"__add__",style:{borderTop:"1px solid #ccc"},children:"+ 添加新素材库"})]}),S.jsx(qd,{className:"absolute right-2 top-2.5 w-4 h-4 text-gray-400 pointer-events-none"})]}),t&&e.length>0&&S.jsx("button",{onClick:W,className:"px-3 py-2 border border-red-300 dark:border-red-600 rounded-lg hover:bg-red-50 dark:hover:bg-red-900 text-red-600 dark:text-red-400 transition-colors",title:"删除当前素材库",children:S.jsx(ow,{className:"w-4 h-4"})})]}),d&&S.jsxs("div",{className:"mt-3 p-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-700",children:[S.jsxs("div",{className:"flex items-center justify-between mb-2",children:[S.jsx("h3",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"添加素材库"}),S.jsx("button",{onClick:()=>p(!1),className:"p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-600",children:S.jsx(vm,{className:"w-4 h-4 text-gray-500"})})]}),S.jsxs("div",{className:"space-y-2",children:[S.jsx("input",{type:"text",placeholder:"素材库名称",value:y,onChange:A=>x(A.target.value),onKeyDown:A=>A.key==="Enter"&&J(),autoFocus:!0,className:"w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"}),S.jsx("input",{type:"text",placeholder:"文件夹路径(例如:C:\\Users\\Pictures)",value:g,onChange:A=>m(A.target.value),onKeyDown:A=>A.key==="Enter"&&J(),className:"w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"}),S.jsxs("div",{className:"flex gap-2",children:[S.jsx("button",{onClick:()=>p(!1),className:"flex-1 px-3 py-1.5 border border-gray-300 dark:border-gray-600 rounded text-sm hover:bg-gray-100 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300",children:"取消"}),S.jsx("button",{onClick:J,disabled:b,className:"flex-1 px-3 py-1.5 bg-blue-500 text-white rounded text-sm hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed",children:b?"添加中...":"添加"})]})]})]})]}),S.jsxs("div",{className:"flex-1 overflow-y-auto p-4",children:[S.jsx("div",{className:"mb-3 space-y-2",children:S.jsxs("div",{className:"flex gap-2",children:[S.jsxs("div",{className:"relative flex-1",children:[S.jsx(Bo,{className:"absolute left-2 top-2 w-4 h-4 text-gray-400"}),S.jsx("input",{type:"text",placeholder:"搜索文件夹(支持多关键词)...",value:c,onChange:A=>M(A.target.value),className:"w-full pl-8 pr-3 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"})]}),S.jsx("button",{onClick:H()?Q:ce,className:"px-2 py-1.5 border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-100 dark:hover:bg-gray-600 text-gray-600 dark:text-gray-400 transition-colors",title:H()?"折叠全部":"展开全部",children:H()?S.jsx(Y1,{className:"w-4 h-4"}):S.jsx(X1,{className:"w-4 h-4"})})]})}),S.jsxs("div",{className:"space-y-1",children:[S.jsxs("div",{className:`flex items-center px-3 py-2 cursor-pointer rounded-md transition-colors ${r===null?"bg-blue-50 dark:bg-blue-900":"hover:bg-gray-100 dark:hover:bg-gray-700"}`,onClick:()=>o(null),children:[S.jsx("div",{className:"w-5 mr-1"}),S.jsx(Zi,{className:"w-4 h-4 mr-2 text-blue-500 flex-shrink-0"}),S.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300 font-medium flex-1",children:"全部图片"}),S.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 ml-2",children:i})]}),(U.length>0||n.length>0)&&S.jsx("div",{className:"h-px bg-gray-200 dark:bg-gray-700 my-2"}),U.length>0?F(U):u?S.jsx("div",{className:"text-center py-8 text-gray-400 dark:text-gray-500 text-sm",children:"未找到匹配的文件夹"}):n.length===0?S.jsx("div",{className:"text-center py-8 text-gray-400 dark:text-gray-500 text-sm",children:"暂无文件夹"}):null]})]})]})}function Ze(){return Ze=Object.assign?Object.assign.bind():function(e){for(var t=1;t"u"||/ServerSideRendering/.test(navigator&&navigator.userAgent)?Z.useEffect:Z.useLayoutEffect;function $r(e,t,n){var r=Z.useRef(t);r.current=t,Z.useEffect(function(){function i(s){r.current(s)}return e&&window.addEventListener(e,i,n),function(){e&&window.removeEventListener(e,i)}},[e])}var fw=["container"];function hw(e){var t=e.container,n=t===void 0?document.body:t,r=fa(e,fw);return Rp.createPortal(ke.createElement("div",Ze({},r)),n)}function pw(e){return ke.createElement("svg",Ze({width:"44",height:"44",viewBox:"0 0 768 768"},e),ke.createElement("path",{d:"M607.5 205.5l-178.5 178.5 178.5 178.5-45 45-178.5-178.5-178.5 178.5-45-45 178.5-178.5-178.5-178.5 45-45 178.5 178.5 178.5-178.5z"}))}function mw(e){return ke.createElement("svg",Ze({width:"44",height:"44",viewBox:"0 0 768 768"},e),ke.createElement("path",{d:"M640.5 352.5v63h-390l178.5 180-45 45-256.5-256.5 256.5-256.5 45 45-178.5 180h390z"}))}function gw(e){return ke.createElement("svg",Ze({width:"44",height:"44",viewBox:"0 0 768 768"},e),ke.createElement("path",{d:"M384 127.5l256.5 256.5-256.5 256.5-45-45 178.5-180h-390v-63h390l-178.5-180z"}))}function yw(){return Z.useEffect(function(){var e=document.body.style,t=e.overflow;return e.overflow="hidden",function(){e.overflow=t}},[]),null}function tf(e){var t=e.touches[0],n=t.clientX,r=t.clientY;if(e.touches.length>=2){var i=e.touches[1],s=i.clientX,o=i.clientY;return[(n+s)/2,(r+o)/2,Math.sqrt(Math.pow(s-n,2)+Math.pow(o-r,2))]}return[n,r,0]}var Vn=function(e,t,n,r){var i,s=n*t,o=(s-r)/2,a=e;return s<=r?(i=1,a=0):e>0&&o-e<=0?(i=2,a=o):e<0&&o+e<=0&&(i=3,a=-o),[i,a]};function qa(e,t,n,r,i,s,o,a,l,d){o===void 0&&(o=innerWidth/2),a===void 0&&(a=innerHeight/2),l===void 0&&(l=0),d===void 0&&(d=0);var p=Vn(e,s,n,innerWidth)[0],y=Vn(t,s,r,innerHeight),x=innerWidth/2,g=innerHeight/2;return{x:o-s/i*(o-(x+e))-x+(r/n>=3&&n*s===innerWidth?0:p?l/2:l),y:a-s/i*(a-(g+t))-g+(y[0]?d/2:d),lastCX:o,lastCY:a}}function nu(e,t,n){var r=e%180!=0;return r?[n,t,r]:[t,n,r]}function Ka(e,t,n){var r=nu(n,innerWidth,innerHeight),i=r[0],s=r[1],o=0,a=i,l=s,d=e/t*s,p=t/e*i;return e=s?a=d:e>=i&&ti/s?l=p:t/e>=3&&!r[2]?o=((l=p)-s)/2:a=d,{width:a,height:l,x:0,y:o,pause:!0}}function Ks(e,t){var n=t.leading,r=n!==void 0&&n,i=t.maxWait,s=t.wait,o=s===void 0?i||0:s,a=Z.useRef(e);a.current=e;var l=Z.useRef(0),d=Z.useRef(),p=function(){return d.current&&clearTimeout(d.current)},y=Z.useCallback(function(){var x=[].slice.call(arguments),g=Date.now();function m(){l.current=g,p(),a.current.apply(null,x)}var u=l.current,v=g-u;if(u===0&&(r&&m(),l.current=g),i!==void 0){if(v>i)return void m()}else v=1&&s&&s())};p()}function p(){l=requestAnimationFrame(d)}}var ww={T:0,L:0,W:0,H:0,FIT:void 0},wm=function(){var e=Z.useRef(!1);return Z.useEffect(function(){return e.current=!0,function(){e.current=!1}},[]),e},xw=["className"];function _w(e){var t=e.className,n=t===void 0?"":t,r=fa(e,xw);return ke.createElement("div",Ze({className:"PhotoView__Spinner "+n},r),ke.createElement("svg",{viewBox:"0 0 32 32",width:"36",height:"36",fill:"white"},ke.createElement("path",{opacity:".25",d:"M16 0 A16 16 0 0 0 16 32 A16 16 0 0 0 16 0 M16 4 A12 12 0 0 1 16 28 A12 12 0 0 1 16 4"}),ke.createElement("path",{d:"M16 0 A16 16 0 0 1 32 16 L28 16 A12 12 0 0 0 16 4z"})))}var kw=["src","loaded","broken","className","onPhotoLoad","loadingElement","brokenElement"];function Sw(e){var t=e.src,n=e.loaded,r=e.broken,i=e.className,s=e.onPhotoLoad,o=e.loadingElement,a=e.brokenElement,l=fa(e,kw),d=wm();return t&&!r?ke.createElement(ke.Fragment,null,ke.createElement("img",Ze({className:"PhotoView__Photo"+(i?" "+i:""),src:t,onLoad:function(p){var y=p.target;d.current&&s({loaded:!0,naturalWidth:y.naturalWidth,naturalHeight:y.naturalHeight})},onError:function(){d.current&&s({broken:!0})},draggable:!1,alt:""},l)),!n&&(o?ke.createElement("span",{className:"PhotoView__icon"},o):ke.createElement(_w,{className:"PhotoView__icon"}))):a?ke.createElement("span",{className:"PhotoView__icon"},typeof a=="function"?a({src:t}):a):null}var bw={naturalWidth:void 0,naturalHeight:void 0,width:void 0,height:void 0,loaded:void 0,broken:!1,x:0,y:0,touched:!1,maskTouched:!1,rotate:0,scale:1,CX:0,CY:0,lastX:0,lastY:0,lastCX:0,lastCY:0,lastScale:1,touchTime:0,touchLength:0,pause:!0,stopRaf:!0,reach:void 0};function Ew(e){var t=e.item,n=t.src,r=t.render,i=t.width,s=i===void 0?0:i,o=t.height,a=o===void 0?0:o,l=t.originRef,d=e.visible,p=e.speed,y=e.easing,x=e.wrapClassName,g=e.className,m=e.style,u=e.loadingElement,v=e.brokenElement,c=e.onPhotoTap,h=e.onMaskTap,w=e.onReachMove,k=e.onReachUp,b=e.onPhotoResize,N=e.isActive,T=e.expose,P=Uo(bw),O=P[0],M=P[1],J=Z.useRef(0),R=wm(),W=O.naturalWidth,_=W===void 0?s:W,V=O.naturalHeight,ce=V===void 0?a:V,Q=O.width,H=Q===void 0?s:Q,U=O.height,ee=U===void 0?a:U,z=O.loaded,F=z===void 0?!n:z,A=O.broken,B=O.x,D=O.y,le=O.touched,de=O.stopRaf,ue=O.maskTouched,se=O.rotate,X=O.scale,re=O.CX,q=O.CY,ne=O.lastX,f=O.lastY,I=O.lastCX,L=O.lastCY,C=O.lastScale,E=O.touchTime,j=O.touchLength,Y=O.pause,G=O.reach,$=li({onScale:function(te){return ie(qs(te))},onRotate:function(te){se!==te&&(T({rotate:te}),M(Ze({rotate:te},Ka(_,ce,te))))}});function ie(te,ge,Ne){X!==te&&(T({scale:te}),M(Ze({scale:te},qa(B,D,H,ee,X,te,ge,Ne),te<=1&&{x:0,y:0})))}var fe=Ks(function(te,ge,Ne){if(Ne===void 0&&(Ne=0),(le||ue)&&N){var mn=nu(se,H,ee),gn=mn[0],Ot=mn[1];if(Ne===0&&J.current===0){var _t=Math.abs(te-re)<=20,kt=Math.abs(ge-q)<=20;if(_t&&kt)return void M({lastCX:te,lastCY:ge});J.current=_t?ge>q?3:2:1}var nn,dr=te-I,Fn=ge-L;if(Ne===0){var fr=Vn(dr+ne,X,gn,innerWidth)[0],zr=Vn(Fn+f,X,Ot,innerHeight);nn=function(Dn,vn,wn,rn){return vn&&Dn===1||rn==="x"?"x":wn&&Dn>1||rn==="y"?"y":void 0}(J.current,fr,zr[0],G),nn!==void 0&&w(nn,te,ge,X)}if(nn==="x"||ue)return void M({reach:"x"});var yn=qs(X+(Ne-j)/100/2*X,_/H,.2);T({scale:yn}),M(Ze({touchLength:Ne,reach:nn,scale:yn},qa(B,D,H,ee,X,yn,te,ge,dr,Fn)))}},{maxWait:8});function oe(te){return!de&&!le&&(R.current&&M(Ze({},te,{pause:d})),R.current)}var pe,ve,ye,We,Jt,at,en,be,pn=(Jt=function(te){return oe({x:te})},at=function(te){return oe({y:te})},en=function(te){return R.current&&(T({scale:te}),M({scale:te})),!le&&R.current},be=li({X:function(te){return Jt(te)},Y:function(te){return at(te)},S:function(te){return en(te)}}),function(te,ge,Ne,mn,gn,Ot,_t,kt,nn,dr,Fn){var fr=nu(dr,gn,Ot),zr=fr[0],yn=fr[1],Dn=Vn(te,kt,zr,innerWidth),vn=Dn[0],wn=Dn[1],rn=Vn(ge,kt,yn,innerHeight),Lr=rn[0],bs=rn[1],Pr=Date.now()-Fn;if(Pr>=200||kt!==_t||Math.abs(nn-_t)>1){var Mn=qa(te,ge,gn,Ot,_t,kt),xn=Mn.x,hr=Mn.y,It=vn?wn:xn!==te?xn:null,Fr=Lr?bs:hr!==ge?hr:null;return It!==null&&yr(te,It,be.X),Fr!==null&&yr(ge,Fr,be.Y),void(kt!==_t&&yr(_t,kt,be.S))}var pr=(te-Ne)/Pr,Bn=(ge-mn)/Pr,Un=Math.sqrt(Math.pow(pr,2)+Math.pow(Bn,2)),_n=!1,kn=!1;(function($t,lt){var ut,Wt=$t,Sn=0,At=0,Dr=function(bi){ut||(ut=bi);var Ei=bi-ut,uc=Math.sign($t),cc=-.001*uc,dc=Math.sign(-Wt)*Math.pow(Wt,2)*2e-4,km=Wt*Ei+(cc+dc)*Math.pow(Ei,2)/2;Sn+=km,ut=bi,uc*(Wt+=(cc+dc)*Ei)<=0?jt():lt(Sn)?sn():jt()};function sn(){At=requestAnimationFrame(Dr)}function jt(){cancelAnimationFrame(At)}sn()})(Un,function($t){var lt=te+$t*(pr/Un),ut=ge+$t*(Bn/Un),Wt=Vn(lt,_t,zr,innerWidth),Sn=Wt[0],At=Wt[1],Dr=Vn(ut,_t,yn,innerHeight),sn=Dr[0],jt=Dr[1];if(Sn&&!_n&&(_n=!0,vn?yr(lt,At,be.X):nf(At,lt+(lt-At),be.X)),sn&&!kn&&(kn=!0,Lr?yr(ut,jt,be.Y):nf(jt,ut+(ut-jt),be.Y)),_n&&kn)return!1;var bi=_n||be.X(At),Ei=kn||be.Y(jt);return bi&&Ei})}),tn=(pe=c,ve=function(te,ge){G||ie(X!==1?1:Math.max(2,_/H),te,ge)},ye=Z.useRef(0),We=Ks(function(){ye.current=0,pe.apply(void 0,[].slice.call(arguments))},{wait:300}),function(){var te=[].slice.call(arguments);ye.current+=1,We.apply(void 0,te),ye.current>=2&&(We.cancel(),ye.current=0,ve.apply(void 0,te))});function tt(te,ge){if(J.current=0,(le||ue)&&N){M({touched:!1,maskTouched:!1,pause:!1,stopRaf:!1,reach:void 0});var Ne=qs(X,_/H);if(pn(B,D,ne,f,H,ee,X,Ne,C,se,E),k(te,ge),re===te&&q===ge){if(le)return void tn(te,ge);ue&&h(te,ge)}}}function Pn(te,ge,Ne){Ne===void 0&&(Ne=0),M({touched:!0,CX:te,CY:ge,lastCX:te,lastCY:ge,lastX:B,lastY:D,lastScale:X,touchLength:Ne,touchTime:Date.now()})}function jr(te){M({maskTouched:!0,CX:te.clientX,CY:te.clientY,lastX:B,lastY:D})}$r(bn?void 0:"mousemove",function(te){te.preventDefault(),fe(te.clientX,te.clientY)}),$r(bn?void 0:"mouseup",function(te){tt(te.clientX,te.clientY)}),$r(bn?"touchmove":void 0,function(te){te.preventDefault();var ge=tf(te);fe.apply(void 0,ge)},{passive:!1}),$r(bn?"touchend":void 0,function(te){var ge=te.changedTouches[0];tt(ge.clientX,ge.clientY)},{passive:!1}),$r("resize",Ks(function(){F&&!le&&(M(Ka(_,ce,se)),b())},{maxWait:8})),tu(function(){N&&T(Ze({scale:X,rotate:se},$))},[N]);var Tt=function(te,ge,Ne,mn,gn,Ot,_t,kt,nn,dr){var Fn=function(xn,hr,It,Fr,pr){var Bn=Z.useRef(!1),Un=Uo({lead:!0,scale:It}),_n=Un[0],kn=_n.lead,$t=_n.scale,lt=Un[1],ut=Ks(function(Wt){try{return pr(!0),lt({lead:!1,scale:Wt}),Promise.resolve()}catch(Sn){return Promise.reject(Sn)}},{wait:Fr});return tu(function(){Bn.current?(pr(!1),lt({lead:!0}),ut(It)):Bn.current=!0},[It]),kn?[xn*$t,hr*$t,It/$t]:[xn*It,hr*It,1]}(Ot,_t,kt,nn,dr),fr=Fn[0],zr=Fn[1],yn=Fn[2],Dn=function(xn,hr,It,Fr,pr){var Bn=Z.useState(ww),Un=Bn[0],_n=Bn[1],kn=Z.useState(0),$t=kn[0],lt=kn[1],ut=Z.useRef(),Wt=li({OK:function(){return xn&<(4)}});function Sn(At){pr(!1),lt(At)}return Z.useEffect(function(){if(ut.current||(ut.current=Date.now()),It){if(function(At,Dr){var sn=At&&At.current;if(sn&&sn.nodeType===1){var jt=sn.getBoundingClientRect();Dr({T:jt.top,L:jt.left,W:jt.width,H:jt.height,FIT:sn.tagName==="IMG"?getComputedStyle(sn).objectFit:void 0})}}(hr,_n),xn)return Date.now()-ut.current<250?(lt(1),requestAnimationFrame(function(){lt(2),requestAnimationFrame(function(){return Sn(3)})}),void setTimeout(Wt.OK,Fr)):void lt(4);Sn(5)}},[xn,It]),[$t,Un]}(te,ge,Ne,nn,dr),vn=Dn[0],wn=Dn[1],rn=wn.W,Lr=wn.FIT,bs=innerWidth/2,Pr=innerHeight/2,Mn=vn<3||vn>4;return[Mn?rn?wn.L:bs:mn+(bs-Ot*kt/2),Mn?rn?wn.T:Pr:gn+(Pr-_t*kt/2),fr,Mn&&Lr?fr*(wn.H/rn):zr,vn===0?yn:Mn?rn/(Ot*kt)||.01:yn,Mn?Lr?1:0:1,vn,Lr]}(d,l,F,B,D,H,ee,X,p,function(te){return M({pause:te})}),_e=Tt[4],Te=Tt[6],Ae="transform "+p+"ms "+y,je={className:g,onMouseDown:bn?void 0:function(te){te.stopPropagation(),te.button===0&&Pn(te.clientX,te.clientY,0)},onTouchStart:bn?function(te){te.stopPropagation(),Pn.apply(void 0,tf(te))}:void 0,onWheel:function(te){if(!G){var ge=qs(X-te.deltaY/100/2,_/H);M({stopRaf:!0}),ie(ge,te.clientX,te.clientY)}},style:{width:Tt[2]+"px",height:Tt[3]+"px",opacity:Tt[5],objectFit:Te===4?void 0:Tt[7],transform:se?"rotate("+se+"deg)":void 0,transition:Te>2?Ae+", opacity "+p+"ms ease, height "+(Te<4?p/2:Te>4?p:0)+"ms "+y:void 0}};return ke.createElement("div",{className:"PhotoView__PhotoWrap"+(x?" "+x:""),style:m,onMouseDown:!bn&&N?jr:void 0,onTouchStart:bn&&N?function(te){return jr(te.touches[0])}:void 0},ke.createElement("div",{className:"PhotoView__PhotoBox",style:{transform:"matrix("+_e+", 0, 0, "+_e+", "+Tt[0]+", "+Tt[1]+")",transition:le||Y?void 0:Ae,willChange:N?"transform":void 0}},n?ke.createElement(Sw,Ze({src:n,loaded:F,broken:A},je,{onPhotoLoad:function(te){M(Ze({},te,te.loaded&&Ka(te.naturalWidth||0,te.naturalHeight||0,se)))},loadingElement:u,brokenElement:v})):r&&r({attrs:je,scale:_e,rotate:se})))}var rf={x:0,touched:!1,pause:!1,lastCX:void 0,lastCY:void 0,bg:void 0,lastBg:void 0,overlay:!0,minimal:!0,scale:1,rotate:0};function Cw(e){var t=e.loop,n=t===void 0?3:t,r=e.speed,i=e.easing,s=e.photoClosable,o=e.maskClosable,a=o===void 0||o,l=e.maskOpacity,d=l===void 0?1:l,p=e.pullClosable,y=p===void 0||p,x=e.bannerVisible,g=x===void 0||x,m=e.overlayRender,u=e.toolbarRender,v=e.className,c=e.maskClassName,h=e.photoClassName,w=e.photoWrapClassName,k=e.loadingElement,b=e.brokenElement,N=e.images,T=e.index,P=T===void 0?0:T,O=e.onIndexChange,M=e.visible,J=e.onClose,R=e.afterClose,W=e.portalContainer,_=Uo(rf),V=_[0],ce=_[1],Q=Z.useState(0),H=Q[0],U=Q[1],ee=V.x,z=V.touched,F=V.pause,A=V.lastCX,B=V.lastCY,D=V.bg,le=D===void 0?d:D,de=V.lastBg,ue=V.overlay,se=V.minimal,X=V.scale,re=V.rotate,q=V.onScale,ne=V.onRotate,f=e.hasOwnProperty("index"),I=f?P:H,L=f?O:U,C=Z.useRef(I),E=N.length,j=N[I],Y=typeof n=="boolean"?n:E>n,G=function(_e,Te){var Ae=Z.useReducer(function(Ne){return!Ne},!1)[1],je=Z.useRef(0),te=function(Ne){var mn=Z.useRef(Ne);function gn(Ot){mn.current=Ot}return Z.useMemo(function(){(function(Ot){_e?(Ot(_e),je.current=1):je.current=2})(gn)},[Ne]),[mn.current,gn]}(_e),ge=te[1];return[te[0],je.current,function(){Ae(),je.current===2&&(ge(!1),Te&&Te()),je.current=0}]}(M,R),$=G[0],ie=G[1],fe=G[2];tu(function(){if($)return ce({pause:!0,x:I*-(innerWidth+Br)}),void(C.current=I);ce(rf)},[$]);var oe=li({close:function(_e){ne&&ne(0),ce({overlay:!0,lastBg:le}),J(_e)},changeIndex:function(_e,Te){Te===void 0&&(Te=!1);var Ae=Y?C.current+(_e-I):_e,je=E-1,te=eu(Ae,0,je),ge=Y?Ae:te,Ne=innerWidth+Br;ce({touched:!1,lastCX:void 0,lastCY:void 0,x:-Ne*ge,pause:Te}),C.current=ge,L&&L(Y?_e<0?je:_e>je?0:_e:te)}}),pe=oe.close,ve=oe.changeIndex;function ye(_e){return _e?pe():ce({overlay:!ue})}function We(){ce({x:-(innerWidth+Br)*I,lastCX:void 0,lastCY:void 0,pause:!0}),C.current=I}function Jt(_e,Te,Ae,je){_e==="x"?function(te){if(A!==void 0){var ge=te-A,Ne=ge;!Y&&(I===0&&ge>0||I===E-1&&ge<0)&&(Ne=ge/2),ce({touched:!0,lastCX:A,x:-(innerWidth+Br)*C.current+Ne,pause:!1})}else ce({touched:!0,lastCX:te,x:ee,pause:!1})}(Te):_e==="y"&&function(te,ge){if(B!==void 0){var Ne=d===null?null:eu(d,.01,d-Math.abs(te-B)/100/4);ce({touched:!0,lastCY:B,bg:ge===1?Ne:d,minimal:ge===1})}else ce({touched:!0,lastCY:te,bg:le,minimal:!0})}(Ae,je)}function at(_e,Te){var Ae=_e-(A??_e),je=Te-(B??Te),te=!1;if(Ae<-40)ve(I+1);else if(Ae>40)ve(I-1);else{var ge=-(innerWidth+Br)*C.current;Math.abs(je)>100&&se&&y&&(te=!0,pe()),ce({touched:!1,x:ge,lastCX:void 0,lastCY:void 0,bg:d,overlay:!!te||ue})}}$r("keydown",function(_e){if(M)switch(_e.key){case"ArrowLeft":ve(I-1,!0);break;case"ArrowRight":ve(I+1,!0);break;case"Escape":pe()}});var en=function(_e,Te,Ae){return Z.useMemo(function(){var je=_e.length;return Ae?_e.concat(_e).concat(_e).slice(je+Te-1,je+Te+2):_e.slice(Math.max(Te-1,0),Math.min(Te+2,je+1))},[_e,Te,Ae])}(N,I,Y);if(!$)return null;var be=ue&&!ie,pn=M?le:de,tn=q&&ne&&{images:N,index:I,visible:M,onClose:pe,onIndexChange:ve,overlayVisible:be,overlay:j&&j.overlay,scale:X,rotate:re,onScale:q,onRotate:ne},tt=r?r(ie):400,Pn=i?i(ie):ef,jr=r?r(3):600,Tt=i?i(3):ef;return ke.createElement(hw,{className:"PhotoView-Portal"+(be?"":" PhotoView-Slider__clean")+(M?"":" PhotoView-Slider__willClose")+(v?" "+v:""),role:"dialog",onClick:function(_e){return _e.stopPropagation()},container:W},M&&ke.createElement(yw,null),ke.createElement("div",{className:"PhotoView-Slider__Backdrop"+(c?" "+c:"")+(ie===1?" PhotoView-Slider__fadeIn":ie===2?" PhotoView-Slider__fadeOut":""),style:{background:pn?"rgba(0, 0, 0, "+pn+")":void 0,transitionTimingFunction:Pn,transitionDuration:(z?0:tt)+"ms",animationDuration:tt+"ms"},onAnimationEnd:fe}),g&&ke.createElement("div",{className:"PhotoView-Slider__BannerWrap"},ke.createElement("div",{className:"PhotoView-Slider__Counter"},I+1," / ",E),ke.createElement("div",{className:"PhotoView-Slider__BannerRight"},u&&tn&&u(tn),ke.createElement(pw,{className:"PhotoView-Slider__toolbarIcon",onClick:pe}))),en.map(function(_e,Te){var Ae=Y||I!==0?C.current-1+Te:I+Te;return ke.createElement(Ew,{key:Y?_e.key+"/"+_e.src+"/"+Ae:_e.key,item:_e,speed:tt,easing:Pn,visible:M,onReachMove:Jt,onReachUp:at,onPhotoTap:function(){return ye(s)},onMaskTap:function(){return ye(a)},wrapClassName:w,className:h,style:{left:(innerWidth+Br)*Ae+"px",transform:"translate3d("+ee+"px, 0px, 0)",transition:z||F?void 0:"transform "+jr+"ms "+Tt},loadingElement:k,brokenElement:b,onPhotoResize:We,isActive:C.current===Ae,expose:ce})}),!bn&&g&&ke.createElement(ke.Fragment,null,(Y||I!==0)&&ke.createElement("div",{className:"PhotoView-Slider__ArrowLeft",onClick:function(){return ve(I-1,!0)}},ke.createElement(mw,null)),(Y||I+1-1){var c=d.slice();return c.splice(v,1,u),void a({images:c})}a(function(h){return{images:h.images.concat(u)}})},remove:function(u){a(function(v){var c=v.images.filter(function(h){return h.key!==u});return{images:c,index:Math.min(c.length-1,y)}})},show:function(u){var v=d.findIndex(function(c){return c.key===u});a({visible:!0,index:v}),r&&r(!0,v,o)}}),g=li({close:function(){a({visible:!1}),r&&r(!1,y,o)},changeIndex:function(u){a({index:u}),n&&n(u,o)}}),m=Z.useMemo(function(){return Ze({},o,x)},[o,x]);return ke.createElement(dw.Provider,{value:m},t,ke.createElement(Cw,Ze({images:d,visible:p,index:y,onIndexChange:g.changeIndex,onClose:g.close},i)))}function ru(){return ru=Object.assign?Object.assign.bind():function(e){for(var t=1;t=t?e.call(null):i.id=requestAnimationFrame(r)}var i={id:requestAnimationFrame(r)};return i}var Ya=-1;function uf(e){if(e===void 0&&(e=!1),Ya===-1||e){var t=document.createElement("div"),n=t.style;n.width="50px",n.height="50px",n.overflow="scroll",document.body.appendChild(t),Ya=t.offsetWidth-t.clientWidth,document.body.removeChild(t)}return Ya}var Ur=null;function cf(e){if(e===void 0&&(e=!1),Ur===null||e){var t=document.createElement("div"),n=t.style;n.width="50px",n.height="50px",n.overflow="scroll",n.direction="rtl";var r=document.createElement("div"),i=r.style;return i.width="100px",i.height="100px",t.appendChild(r),document.body.appendChild(t),t.scrollLeft>0?Ur="positive-descending":(t.scrollLeft=1,t.scrollLeft===0?Ur="negative":Ur="positive-ascending"),document.body.removeChild(t),Ur}return Ur}var Lw=150,Pw=function(t,n){return t};function Fw(e){var t,n=e.getItemOffset,r=e.getEstimatedTotalSize,i=e.getItemSize,s=e.getOffsetForIndexAndAlignment,o=e.getStartIndexForOffset,a=e.getStopIndexForStartIndex,l=e.initInstanceProps,d=e.shouldResetStyleCacheOnItemSizeChange,p=e.validateProps;return t=function(y){Ow(x,y);function x(m){var u;return u=y.call(this,m)||this,u._instanceProps=l(u.props,sf(u)),u._outerRef=void 0,u._resetIsScrollingTimeoutId=null,u.state={instance:sf(u),isScrolling:!1,scrollDirection:"forward",scrollOffset:typeof u.props.initialScrollOffset=="number"?u.props.initialScrollOffset:0,scrollUpdateWasRequested:!1},u._callOnItemsRendered=void 0,u._callOnItemsRendered=Xa(function(v,c,h,w){return u.props.onItemsRendered({overscanStartIndex:v,overscanStopIndex:c,visibleStartIndex:h,visibleStopIndex:w})}),u._callOnScroll=void 0,u._callOnScroll=Xa(function(v,c,h){return u.props.onScroll({scrollDirection:v,scrollOffset:c,scrollUpdateWasRequested:h})}),u._getItemStyle=void 0,u._getItemStyle=function(v){var c=u.props,h=c.direction,w=c.itemSize,k=c.layout,b=u._getItemStyleCache(d&&w,d&&k,d&&h),N;if(b.hasOwnProperty(v))N=b[v];else{var T=n(u.props,v,u._instanceProps),P=i(u.props,v,u._instanceProps),O=h==="horizontal"||k==="horizontal",M=h==="rtl",J=O?T:0;b[v]=N={position:"absolute",left:M?void 0:J,right:M?J:void 0,top:O?0:T,height:O?"100%":P,width:O?P:"100%"}}return N},u._getItemStyleCache=void 0,u._getItemStyleCache=Xa(function(v,c,h){return{}}),u._onScrollHorizontal=function(v){var c=v.currentTarget,h=c.clientWidth,w=c.scrollLeft,k=c.scrollWidth;u.setState(function(b){if(b.scrollOffset===w)return null;var N=u.props.direction,T=w;if(N==="rtl")switch(cf()){case"negative":T=-w;break;case"positive-descending":T=k-h-w;break}return T=Math.max(0,Math.min(T,k-h)),{isScrolling:!0,scrollDirection:b.scrollOffsetN.clientWidth?uf():0:b=N.scrollHeight>N.clientHeight?uf():0}this.scrollTo(s(this.props,u,v,k,this._instanceProps,b))},g.componentDidMount=function(){var u=this.props,v=u.direction,c=u.initialScrollOffset,h=u.layout;if(typeof c=="number"&&this._outerRef!=null){var w=this._outerRef;v==="horizontal"||h==="horizontal"?w.scrollLeft=c:w.scrollTop=c}this._callPropsCallbacks()},g.componentDidUpdate=function(){var u=this.props,v=u.direction,c=u.layout,h=this.state,w=h.scrollOffset,k=h.scrollUpdateWasRequested;if(k&&this._outerRef!=null){var b=this._outerRef;if(v==="horizontal"||c==="horizontal")if(v==="rtl")switch(cf()){case"negative":b.scrollLeft=-w;break;case"positive-ascending":b.scrollLeft=w;break;default:var N=b.clientWidth,T=b.scrollWidth;b.scrollLeft=T-N-w;break}else b.scrollLeft=w;else b.scrollTop=w}this._callPropsCallbacks()},g.componentWillUnmount=function(){this._resetIsScrollingTimeoutId!==null&&lf(this._resetIsScrollingTimeoutId)},g.render=function(){var u=this.props,v=u.children,c=u.className,h=u.direction,w=u.height,k=u.innerRef,b=u.innerElementType,N=u.innerTagName,T=u.itemCount,P=u.itemData,O=u.itemKey,M=O===void 0?Pw:O,J=u.layout,R=u.outerElementType,W=u.outerTagName,_=u.style,V=u.useIsScrolling,ce=u.width,Q=this.state.isScrolling,H=h==="horizontal"||J==="horizontal",U=H?this._onScrollHorizontal:this._onScrollVertical,ee=this._getRangeToRender(),z=ee[0],F=ee[1],A=[];if(T>0)for(var B=z;B<=F;B++)A.push(Z.createElement(v,{data:P,key:M(B,P),index:B,isScrolling:V?Q:void 0,style:this._getItemStyle(B)}));var D=r(this.props,this._instanceProps);return Z.createElement(R||W||"div",{className:c,onScroll:U,ref:this._outerRefSetter,style:ru({position:"relative",height:w,width:ce,overflow:"auto",WebkitOverflowScrolling:"touch",willChange:"transform",direction:h},_)},Z.createElement(b||N||"div",{children:A,ref:k,style:{height:H?"100%":D,pointerEvents:Q?"none":void 0,width:H?D:"100%"}}))},g._callPropsCallbacks=function(){if(typeof this.props.onItemsRendered=="function"){var u=this.props.itemCount;if(u>0){var v=this._getRangeToRender(),c=v[0],h=v[1],w=v[2],k=v[3];this._callOnItemsRendered(c,h,w,k)}}if(typeof this.props.onScroll=="function"){var b=this.state,N=b.scrollDirection,T=b.scrollOffset,P=b.scrollUpdateWasRequested;this._callOnScroll(N,T,P)}},g._getRangeToRender=function(){var u=this.props,v=u.itemCount,c=u.overscanCount,h=this.state,w=h.isScrolling,k=h.scrollDirection,b=h.scrollOffset;if(v===0)return[0,0,0,0];var N=o(this.props,b,this._instanceProps),T=a(this.props,N,b,this._instanceProps),P=!w||k==="backward"?Math.max(1,c):1,O=!w||k==="forward"?Math.max(1,c):1;return[Math.max(0,N-P),Math.max(0,Math.min(v-1,T+O)),N,T]},x}(Z.PureComponent),t.defaultProps={direction:"ltr",itemData:void 0,layout:"vertical",overscanCount:2,useIsScrolling:!1},t}var Dw=function(t,n){t.children,t.direction,t.height,t.layout,t.innerTagName,t.outerTagName,t.width,n.instance},Mw=50,ti=function(t,n,r){var i=t,s=i.itemSize,o=r.itemMetadataMap,a=r.lastMeasuredIndex;if(n>a){var l=0;if(a>=0){var d=o[a];l=d.offset+d.size}for(var p=a+1;p<=n;p++){var y=s(p);o[p]={offset:l,size:y},l+=y}r.lastMeasuredIndex=n}return o[n]},Bw=function(t,n,r){var i=n.itemMetadataMap,s=n.lastMeasuredIndex,o=s>0?i[s].offset:0;return o>=r?xm(t,n,s,0,r):Uw(t,n,Math.max(0,s),r)},xm=function(t,n,r,i,s){for(;i<=r;){var o=i+Math.floor((r-i)/2),a=ti(t,o,n).offset;if(a===s)return o;as&&(r=o-1)}return i>0?i-1:0},Uw=function(t,n,r,i){for(var s=t.itemCount,o=1;r=r&&(o=r-1),o>=0){var l=i[o];a=l.offset+l.size}var d=r-o-1,p=d*s;return a+p},$w=Fw({getItemOffset:function(t,n,r){return ti(t,n,r).offset},getItemSize:function(t,n,r){return r.itemMetadataMap[n].size},getEstimatedTotalSize:df,getOffsetForIndexAndAlignment:function(t,n,r,i,s,o){var a=t.direction,l=t.height,d=t.layout,p=t.width,y=a==="horizontal"||d==="horizontal",x=y?p:l,g=ti(t,n,s),m=df(t,s),u=Math.max(0,Math.min(m-x,g.offset)),v=Math.max(0,g.offset-x+g.size+o);switch(r==="smart"&&(i>=v-x&&i<=u+x?r="auto":r="center"),r){case"start":return u;case"end":return v;case"center":return Math.round(v+(u-v)/2);case"auto":default:return i>=v&&i<=u?i:i{try{await Me.openInExplorer(t,e.path)}catch(o){console.error("Failed to open file:",o)}};return S.jsxs("div",{className:"fixed inset-0 z-50 bg-black bg-opacity-90 flex items-center justify-center",children:[S.jsxs("div",{className:"absolute top-0 left-0 right-0 h-16 bg-black bg-opacity-50 flex items-center justify-between px-4 z-10",children:[S.jsx("div",{className:"text-white text-sm truncate max-w-md",children:e.filename}),S.jsxs("div",{className:"flex items-center gap-2",children:[S.jsx("button",{onClick:s,className:"p-2 text-white hover:bg-white hover:bg-opacity-20 rounded transition-colors",title:"在系统默认应用中打开",children:S.jsx(G1,{className:"w-5 h-5"})}),S.jsx("button",{onClick:n,className:"p-2 text-white hover:bg-white hover:bg-opacity-20 rounded transition-colors",children:S.jsx(vm,{className:"w-6 h-6"})})]})]}),S.jsxs("div",{className:"w-full h-full flex items-center justify-center p-20",children:[r==="video"&&S.jsx("video",{src:i,controls:!0,autoPlay:!0,className:"max-w-full max-h-full rounded shadow-2xl",onError:o=>{console.error("Video load error:",o),alert("视频加载失败,请尝试在系统默认应用中打开")},children:"您的浏览器不支持视频播放"}),r==="audio"&&S.jsxs("div",{className:"flex flex-col items-center justify-center",children:[S.jsx("div",{className:"text-white text-6xl mb-8",children:"🎵"}),S.jsx("audio",{src:i,controls:!0,autoPlay:!0,className:"w-96 rounded shadow-2xl",onError:o=>{console.error("Audio load error:",o),alert("音频加载失败,请尝试在系统默认应用中打开")},children:"您的浏览器不支持音频播放"}),S.jsx("p",{className:"text-white mt-4 text-sm opacity-70",children:e.filename})]}),r==="document"&&S.jsx("div",{className:"w-full h-full bg-white rounded shadow-2xl overflow-hidden",children:e.format==="pdf"?S.jsx("iframe",{src:i,className:"w-full h-full",title:e.filename}):S.jsx("iframe",{src:i,className:"w-full h-full",title:e.filename,sandbox:"allow-same-origin"})}),(r==="design"||r==="other"||!r)&&S.jsxs("div",{className:"text-center text-white",children:[S.jsx("p",{className:"mb-4",children:"此文件类型需要在专业软件中打开"}),S.jsx("button",{onClick:s,className:"px-6 py-3 bg-blue-500 hover:bg-blue-600 rounded-lg transition-colors",children:"在系统默认应用中打开"})]})]}),S.jsx("div",{className:"absolute inset-0 -z-10",onClick:n})]})}const Hw=100,Vw=500;function qw(){const{filteredImages:e,currentLibraryId:t,thumbnailHeight:n,selectedImage:r,setSelectedImage:i,selectedImages:s,setSelectedImages:o,toggleImageSelection:a,clearSelection:l,isResizingPanels:d,imageLoadingState:p,selectedFolder:y,searchKeywords:x,filters:g,appendImages:m,setImageLoadingState:u}=me(),v=Z.useRef(null),c=Z.useRef(null),h=Z.useRef(null),w=Z.useRef(0),[k,b]=Z.useState(0),[N,T]=Z.useState(0),[P,O]=Z.useState(-1),[M,J]=Z.useState(null),[R,W]=Z.useState(null),[_,V]=Z.useState([]),ce=Z.useCallback(async()=>{var ne;if(!t||!p.hasMore||p.isLoading)return;const q=Ft.createRequest(ps.IMAGES);u({isLoading:!0});try{const f={offset:p.loadedCount,limit:200};y&&(f.folder=y),x&&(f.keywords=x),((ne=g.formats)==null?void 0:ne.length)>0&&(f.formats=g.formats.join(","));const I=await Me.search(t,f,{signal:q.signal});if(!Ft.isValid(q.id))return;const{images:L,total:C,hasMore:E}=I.data;Ft.complete(q.id),m(L),u({isLoading:!1,loadedCount:p.loadedCount+L.length,totalCount:C,hasMore:E||!1})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError")return;console.error("Error loading more images:",f),Ft.error(q.id),u({isLoading:!1})}},[t,p,y,x,g,m,u]);Z.useEffect(()=>{let q=null,ne=0;const f=10,I={current:0};let L=null;const C=(Y,G)=>(Math.abs(Y-I.current)<12||(I.current=Y,L&&clearTimeout(L),L=setTimeout(()=>{b(Y),T(G)},50)),!0),E=()=>{if(v.current){const Y=v.current.offsetWidth-32,G=v.current.offsetHeight;if(Y>0)return C(Y,G)}return!1},j=()=>{E()?v.current&&(q=new ResizeObserver(()=>{me.getState().isResizingPanels||E()}),q.observe(v.current)):ne{q&&q.disconnect(),L&&clearTimeout(L)}},[]),Z.useEffect(()=>{if(d||!v.current)return;const q=v.current.offsetWidth-32,ne=v.current.offsetHeight;q>0&&(b(q),T(ne),c.current&&c.current.resetAfterIndex(0))},[d]);const Q=e.length>Vw,H=Z.useRef({length:0,firstId:null,libraryId:null}),U=Z.useRef(!1);Z.useEffect(()=>{var E;const q=H.current.length,ne=e.length,f=H.current.firstId,I=(E=e[0])==null?void 0:E.id,L=H.current.libraryId;q>0&&ne===0||I!==f||t!==L?(V([]),w.current=0,U.current=!1,h.current&&h.current.postMessage({reset:!0,requestId:0})):ne>q&&(U.current=!0),H.current={length:ne,firstId:I,libraryId:t}},[e,t]),Z.useEffect(()=>(typeof Worker<"u"&&(h.current=new Worker(new URL("/assets/layoutWorker-D6X91dDa.js",import.meta.url),{type:"module"}),h.current.onmessage=q=>{const{rows:ne,requestId:f}=q.data;f===w.current&&V(ne)}),()=>{h.current&&(h.current.terminate(),h.current=null)}),[]),Z.useEffect(()=>{if(!Q||!h.current||!e.length||!k)return;const q=++w.current,ne=e.map(f=>({id:f.id,width:f.width,height:f.height,filename:f.filename,thumbnail_path:f.thumbnail_path,path:f.path,file_type:f.file_type,format:f.format}));h.current.postMessage({images:ne,containerWidth:k,targetHeight:n,requestId:q,incremental:U.current})},[e,k,n,Q]);const ee=Z.useMemo(()=>{if(Q)return[];if(!e.length||!k)return[];const q=16,ne=n,f=[];let I=[],L=0;return e.forEach((C,E)=>{const j=C.width/C.height,Y=ne*j;I.push({...C,originalWidth:Y,aspectRatio:j}),L+=Y;const G=(I.length-1)*q,$=L+G,ie=E===e.length-1;let fe=!1;if(ie)fe=!0;else if($>=k*.95)fe=!0;else{const oe=e[E+1];if(oe){const pe=oe.width/oe.height,ve=ne*pe;L+ve+I.length*q>k*1.2&&(fe=!0)}}if(fe){const oe=(I.length-1)*q;let ve=(k-oe)/L;ie&&I.length<3&&(ve=Math.min(ve,1.2));const ye=ne*ve;I=I.map(We=>({...We,calculatedWidth:We.originalWidth*ve,calculatedHeight:ye})),f.push(I),I=[],L=0}}),f},[e,n,k,Q]),z=Q?_:ee,F=q=>{if(!t||!q.thumbnail_path)return"";const ne=q.thumbnail_path.replace(/\\/g,"/").split("/").pop();return Me.getThumbnailUrl(t,"480",ne)},A=q=>t?Me.getOriginalUrl(t,q.path):"",B=Z.useMemo(()=>e.map(q=>({src:A(q),key:q.id})),[e,t]),D=e.length>Hw,le=Z.useCallback(q=>!z[q]||z[q].length===0?n+40:z[q][0].calculatedHeight+28+32,[z,n]),de=Z.useRef(0);Z.useEffect(()=>{if(c.current&&D){const q=de.current,ne=z.length;ne>q&&q>0?c.current.resetAfterIndex(Math.max(0,q-1)):c.current.resetAfterIndex(0),de.current=ne}},[z,D]);const ue=Z.useMemo(()=>z.flat(),[z]),se=Z.useCallback((q,ne,f)=>{if(ne.ctrlKey||ne.metaKey)ne.preventDefault(),a(q),J(f);else if(ne.shiftKey&&M!==null){ne.preventDefault();const I=Math.min(M,f),L=Math.max(M,f),C=ue.slice(I,L+1);o(C)}else l(),i(q),J(f)},[ue,M,a,o,l,i]),X=(q,ne)=>{const f=(r==null?void 0:r.id)===q.id,I=s.some(C=>C.id===q.id),L=f||I;return S.jsxs("div",{className:"flex-shrink-0",style:{width:`${q.calculatedWidth}px`},children:[S.jsxs("div",{className:"relative group cursor-pointer overflow-hidden rounded-lg transition-all hover:shadow-lg",style:{height:`${q.calculatedHeight}px`,backgroundColor:"#2a2a2a",border:L?"3px solid #3b82f6":"3px solid transparent"},onClick:C=>se(q,C,ne),onDoubleClick:()=>{(q.file_type||"image")==="image"?O(ne):W(q)},children:[S.jsx("img",{src:F(q),alt:q.filename,className:"w-full h-full object-cover",loading:"lazy",onError:C=>{C.target.style.display="none"}}),q.file_type&&q.file_type!=="image"&&S.jsxs("div",{className:`absolute top-2 right-2 rounded-md px-2 py-1 flex items-center gap-1 shadow-lg ${q.file_type==="video"?"bg-blue-500 bg-opacity-90":q.file_type==="audio"?"bg-pink-500 bg-opacity-90":q.file_type==="document"?"bg-green-500 bg-opacity-90":q.file_type==="design"?"bg-purple-500 bg-opacity-90":"bg-gray-500 bg-opacity-90"}`,children:[q.file_type==="video"&&S.jsx(ym,{className:"w-4 h-4 text-white fill-white"}),q.file_type==="audio"&&S.jsx(rw,{className:"w-4 h-4 text-white"}),q.file_type==="document"&&S.jsx(J1,{className:"w-4 h-4 text-white"}),q.file_type==="design"&&S.jsx(iw,{className:"w-4 h-4 text-white"}),q.file_type==="other"&&S.jsx(ew,{className:"w-4 h-4 text-white"}),S.jsx("span",{className:"text-white text-xs font-semibold uppercase",children:q.format||q.filename.split(".").pop()})]}),S.jsx("div",{className:"absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-all pointer-events-none"})]}),S.jsx("div",{className:"mt-1 px-1",children:S.jsx("p",{className:"text-xs truncate text-center transition-colors",style:{color:L?"#3b82f6":"#909090",fontWeight:L?"600":"400"},children:q.filename})})]},q.id)},re=({index:q,style:ne})=>{var L;const f=z[q];if(!f)return null;let I=0;for(let C=0;CX(C,I+E))})};return e.length?Q&&z.length===0&&e.length>0&&k>0?S.jsx("div",{ref:v,className:"flex items-center justify-center h-full text-gray-500 dark:text-gray-400",children:S.jsxs("div",{className:"text-center",children:[S.jsx("div",{className:"animate-spin w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full mx-auto mb-2"}),S.jsx("p",{className:"text-sm",children:"正在计算布局..."})]})}):!k&&e.length>0?S.jsx("div",{ref:v,className:"h-full overflow-hidden"}):S.jsxs("div",{ref:v,className:"h-full overflow-hidden",children:[S.jsx(Tw,{images:B,visible:P>=0,onClose:()=>O(-1),index:P,onIndexChange:O,children:D?S.jsx($w,{ref:c,height:N||600,width:k+32,itemCount:z.length,itemSize:le,className:"p-4",overscanCount:3,onScroll:({scrollOffset:q,scrollDirection:ne})=>{if(ne==="forward"&&p.hasMore&&!p.isLoading){const f=z.reduce((L,C,E)=>L+le(E),0),I=q+(N||600);f-I<500&&ce()}},children:re}):S.jsx("div",{className:"h-full overflow-y-auto p-4",onScroll:q=>{if(p.hasMore&&!p.isLoading){const{scrollTop:ne,scrollHeight:f,clientHeight:I}=q.target;f-ne-I<500&&ce()}},children:S.jsx("div",{className:"space-y-8",children:z.map((q,ne)=>{var I;let f=0;for(let L=0;LX(L,f+C))},ne)})})})}),R&&S.jsx(Ww,{file:R,libraryId:t,onClose:()=>W(null)})]}):S.jsx("div",{ref:v,className:"flex items-center justify-center h-full text-gray-500 dark:text-gray-400",children:S.jsxs("div",{className:"text-center",children:[S.jsx("p",{className:"text-lg mb-2",children:"暂无图片"}),S.jsx("p",{className:"text-sm",children:"请添加素材库或调整搜索条件"})]})})}function Kw(){const{totalImageCount:e,folders:t,currentLibraryId:n,getCurrentLibrary:r}=me(),i=r(),s=t.length,o=t.filter(a=>!a.parent_path||a.parent_path==="."||a.parent_path==="");return S.jsx("div",{className:"flex-1 h-full overflow-y-auto bg-gray-50 dark:bg-gray-900 p-8",children:S.jsxs("div",{className:"max-w-4xl mx-auto",children:[S.jsxs("div",{className:"mb-8",children:[S.jsx("h1",{className:"text-3xl font-bold text-gray-900 dark:text-white mb-2",children:(i==null?void 0:i.name)||"素材库"}),S.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:i==null?void 0:i.path})]}),S.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6 mb-12",children:[S.jsx("div",{className:"bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm border border-gray-100 dark:border-gray-700",children:S.jsxs("div",{className:"flex items-center gap-4",children:[S.jsx("div",{className:"p-3 bg-blue-100 dark:bg-blue-900/30 rounded-lg text-blue-600 dark:text-blue-400",children:S.jsx(nw,{className:"w-6 h-6"})}),S.jsxs("div",{children:[S.jsx("div",{className:"text-2xl font-bold text-gray-900 dark:text-white",children:e.toLocaleString()}),S.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"总图片数"})]})]})}),S.jsx("div",{className:"bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm border border-gray-100 dark:border-gray-700",children:S.jsxs("div",{className:"flex items-center gap-4",children:[S.jsx("div",{className:"p-3 bg-indigo-100 dark:bg-indigo-900/30 rounded-lg text-indigo-600 dark:text-indigo-400",children:S.jsx(Zi,{className:"w-6 h-6"})}),S.jsxs("div",{children:[S.jsx("div",{className:"text-2xl font-bold text-gray-900 dark:text-white",children:s.toLocaleString()}),S.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"文件夹"})]})]})}),S.jsx("div",{className:"bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm border border-gray-100 dark:border-gray-700",children:S.jsxs("div",{className:"flex items-center gap-4",children:[S.jsx("div",{className:"p-3 bg-purple-100 dark:bg-purple-900/30 rounded-lg text-purple-600 dark:text-purple-400",children:S.jsx(Bo,{className:"w-6 h-6"})}),S.jsxs("div",{children:[S.jsx("div",{className:"text-sm font-medium text-gray-900 dark:text-white mb-1",children:"快速开始"}),S.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:"使用左侧目录树浏览或顶部搜索栏查找图片"})]})]})})]}),o.length>0&&S.jsxs("div",{children:[S.jsx("h2",{className:"text-xl font-semibold text-gray-900 dark:text-white mb-4",children:"根目录文件夹"}),S.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",children:o.map(a=>S.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg p-4 shadow-sm border border-gray-100 dark:border-gray-700 hover:shadow-md transition-shadow cursor-pointer group",onClick:()=>me.getState().setSelectedFolder(a.path),children:[S.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[S.jsx(Zi,{className:"w-8 h-8 text-yellow-500 group-hover:text-yellow-400 transition-colors"}),S.jsx("div",{className:"flex-1 min-w-0",children:S.jsx("div",{className:"font-medium text-gray-900 dark:text-white truncate",title:a.name,children:a.name})})]}),S.jsxs("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:[a.image_count||0," 张图片"]})]},a.path))})]}),o.length===0&&S.jsxs("div",{className:"text-center py-12 bg-white dark:bg-gray-800 rounded-xl border border-dashed border-gray-300 dark:border-gray-700",children:[S.jsx(Zi,{className:"w-12 h-12 text-gray-300 dark:text-gray-600 mx-auto mb-4"}),S.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-white mb-2",children:"暂无文件夹"}),S.jsx("p",{className:"text-gray-500 dark:text-gray-400 max-w-sm mx-auto",children:"您的素材库似乎是空的。请将图片添加到素材库目录中,系统会自动扫描。"})]})]})})}function ff(){const{currentLibraryId:e,searchKeywords:t,filters:n,selectedFolder:r,setImages:i,scanProgress:s,imageLoadingState:o}=me(),a=Z.useRef(null),l=Z.useRef(null),[d,p]=Z.useState(!1),[y,x]=Z.useState(!1),g=()=>{if(!s||s.current===0)return null;if(s.estimatedTimeLeft!==void 0){const h=s.estimatedTimeLeft;return h<1?"即将完成":h<60?`剩余约 ${h} 秒`:`剩余约 ${Math.floor(h/60)} 分钟`}return null},m=Z.useCallback(()=>{Ft.cancelAll(ps.IMAGES),a.current=null},[]),u=Z.useCallback(async()=>{var w;if(!e)return;if(!r&&!t&&n.formats.length===0){i([]),me.getState().setImageLoadingState({isLoading:!1,loadedCount:0,totalCount:0,hasMore:!1});return}Jl(),m();const h=Ft.createRequest(ps.IMAGES);a.current=h,me.getState().setImageLoadingState({isLoading:!0,loadedCount:0,totalCount:0,hasMore:!1});try{const k={offset:0,limit:200};r&&(k.folder=r),t&&(k.keywords=t),((w=n.formats)==null?void 0:w.length)>0&&(k.formats=n.formats.join(","));const b=await Me.search(e,k,{signal:h.signal});if(!Ft.isValid(h.id))return;const{images:N,total:T,hasMore:P}=b.data;Ft.complete(h.id),i(N),me.getState().setImageLoadingState({isLoading:!1,loadedCount:N.length,totalCount:T||N.length,hasMore:P||!1}),P&&uw(P)}catch(k){if(k.name==="CanceledError"||k.name==="AbortError")return;console.error("Error loading images:",k),Ft.error(h.id)}finally{(Ft.isValid(h.id)||h.status==="completed")&&(a.current=null)}},[e,t,n,r,i,m]);Z.useEffect(()=>{if(e)return l.current&&clearTimeout(l.current),m(),i([]),l.current=setTimeout(()=>{u()},50),()=>{l.current&&clearTimeout(l.current)}},[e,t,n,r,u,m,i]),Z.useEffect(()=>()=>{m(),l.current&&clearTimeout(l.current)},[m]);const v=async()=>{if(!(!e||y)){x(!0);try{await sr.stop(e),p(!0)}catch(h){console.error("Error stopping scan:",h)}finally{x(!1)}}},c=async()=>{if(!(!e||y)){x(!0);try{s!=null&&s.needsRescan?await sr.sync(e):await sr.resume(e),p(!1)}catch(h){console.error("Error resuming scan:",h)}finally{x(!1)}}};return Z.useEffect(()=>{s?s.isPaused?p(!0):s.percent===100&&p(!1):p(!1)},[s]),S.jsxs("div",{className:"flex flex-col h-full bg-gray-50 dark:bg-gray-900",children:[s&&S.jsxs("div",{className:`p-4 border-b ${d?"bg-yellow-50 dark:bg-yellow-900 border-yellow-200 dark:border-yellow-700":"bg-blue-50 dark:bg-blue-900 border-blue-200 dark:border-blue-700"}`,children:[S.jsxs("div",{className:"flex items-center justify-between mb-2",children:[S.jsx("div",{className:`text-sm font-medium ${d?"text-yellow-700 dark:text-yellow-300":"text-blue-700 dark:text-blue-300"}`,children:d?"扫描已暂停":(s==null?void 0:s.status)==="preparing"?"正在准备扫描...":"正在扫描素材库,期间建议勿操作,否则会影响扫描速度"}),S.jsxs("div",{className:"flex items-center gap-2",children:[S.jsxs("span",{className:`text-sm ${d?"text-yellow-600":"text-blue-600"}`,children:[(s==null?void 0:s.percent)||0,"%"]}),((s==null?void 0:s.canStop)||d)&&S.jsx("button",{onClick:d?c:v,disabled:y,className:`p-1.5 rounded-md ${d?"bg-green-500 hover:bg-green-600":"bg-yellow-500 hover:bg-yellow-600"} text-white`,children:d?S.jsx(ym,{className:"w-4 h-4"}):S.jsx(sw,{className:"w-4 h-4"})})]})]}),S.jsx("div",{className:`w-full rounded-full h-2 mb-2 ${d?"bg-yellow-200":"bg-blue-200"}`,children:S.jsx("div",{className:`h-2 rounded-full transition-all ${d?"bg-yellow-500":"bg-blue-500"}`,style:{width:`${(s==null?void 0:s.percent)||0}%`}})}),S.jsxs("div",{className:`text-xs ${d?"text-yellow-600":"text-blue-600"}`,children:["已处理 ",(s==null?void 0:s.current)||0," / ",(s==null?void 0:s.total)||0," 张图片",g()&&` · ${g()}`]})]}),o.hasMore&&o.loadedCount>0&&S.jsx("div",{className:"px-4 py-2 bg-gray-100 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700",children:S.jsxs("div",{className:"flex items-center justify-between text-sm",children:[S.jsxs("span",{className:"text-gray-600 dark:text-gray-400",children:["已加载 ",o.loadedCount," / ",o.totalCount," 张"]}),S.jsx("div",{className:"w-32 h-1.5 bg-gray-200 rounded-full overflow-hidden",children:S.jsx("div",{className:"h-full bg-blue-500",style:{width:`${o.loadedCount/o.totalCount*100}%`}})})]})}),S.jsx("div",{className:"flex-1 overflow-hidden",children:!r&&!t&&n.formats.length===0?S.jsx(Kw,{}):S.jsx(qw,{})})]})}function Xs(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var _m={exports:{}};/*! - -JSZip v3.10.1 - A JavaScript class for generating and reading zip files - - -(c) 2009-2016 Stuart Knightley -Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. - -JSZip uses the library pako released under the MIT license : -https://github.com/nodeca/pako/blob/main/LICENSE -*/(function(e,t){(function(n){e.exports=n()})(function(){return function n(r,i,s){function o(d,p){if(!i[d]){if(!r[d]){var y=typeof Xs=="function"&&Xs;if(!p&&y)return y(d,!0);if(a)return a(d,!0);var x=new Error("Cannot find module '"+d+"'");throw x.code="MODULE_NOT_FOUND",x}var g=i[d]={exports:{}};r[d][0].call(g.exports,function(m){var u=r[d][1][m];return o(u||m)},g,g.exports,n,r,i,s)}return i[d].exports}for(var a=typeof Xs=="function"&&Xs,l=0;l>2,g=(3&d)<<4|p>>4,m=1>6:64,u=2>4,p=(15&x)<<4|(g=a.indexOf(l.charAt(u++)))>>2,y=(3&g)<<6|(m=a.indexOf(l.charAt(u++))),h[v++]=d,g!==64&&(h[v++]=p),m!==64&&(h[v++]=y);return h}},{"./support":30,"./utils":32}],2:[function(n,r,i){var s=n("./external"),o=n("./stream/DataWorker"),a=n("./stream/Crc32Probe"),l=n("./stream/DataLengthProbe");function d(p,y,x,g,m){this.compressedSize=p,this.uncompressedSize=y,this.crc32=x,this.compression=g,this.compressedContent=m}d.prototype={getContentWorker:function(){var p=new o(s.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new l("data_length")),y=this;return p.on("end",function(){if(this.streamInfo.data_length!==y.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),p},getCompressedWorker:function(){return new o(s.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},d.createWorkerFrom=function(p,y,x){return p.pipe(new a).pipe(new l("uncompressedSize")).pipe(y.compressWorker(x)).pipe(new l("compressedSize")).withStreamInfo("compression",y)},r.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,r,i){var s=n("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new s("STORE compression")},uncompressWorker:function(){return new s("STORE decompression")}},i.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,r,i){var s=n("./utils"),o=function(){for(var a,l=[],d=0;d<256;d++){a=d;for(var p=0;p<8;p++)a=1&a?3988292384^a>>>1:a>>>1;l[d]=a}return l}();r.exports=function(a,l){return a!==void 0&&a.length?s.getTypeOf(a)!=="string"?function(d,p,y,x){var g=o,m=x+y;d^=-1;for(var u=x;u>>8^g[255&(d^p[u])];return-1^d}(0|l,a,a.length,0):function(d,p,y,x){var g=o,m=x+y;d^=-1;for(var u=x;u>>8^g[255&(d^p.charCodeAt(u))];return-1^d}(0|l,a,a.length,0):0}},{"./utils":32}],5:[function(n,r,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(n,r,i){var s=null;s=typeof Promise<"u"?Promise:n("lie"),r.exports={Promise:s}},{lie:37}],7:[function(n,r,i){var s=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",o=n("pako"),a=n("./utils"),l=n("./stream/GenericWorker"),d=s?"uint8array":"array";function p(y,x){l.call(this,"FlateWorker/"+y),this._pako=null,this._pakoAction=y,this._pakoOptions=x,this.meta={}}i.magic="\b\0",a.inherits(p,l),p.prototype.processChunk=function(y){this.meta=y.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(d,y.data),!1)},p.prototype.flush=function(){l.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},p.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this._pako=null},p.prototype._createPako=function(){this._pako=new o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var y=this;this._pako.onData=function(x){y.push({data:x,meta:y.meta})}},i.compressWorker=function(y){return new p("Deflate",y)},i.uncompressWorker=function(){return new p("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,i){function s(g,m){var u,v="";for(u=0;u>>=8;return v}function o(g,m,u,v,c,h){var w,k,b=g.file,N=g.compression,T=h!==d.utf8encode,P=a.transformTo("string",h(b.name)),O=a.transformTo("string",d.utf8encode(b.name)),M=b.comment,J=a.transformTo("string",h(M)),R=a.transformTo("string",d.utf8encode(M)),W=O.length!==b.name.length,_=R.length!==M.length,V="",ce="",Q="",H=b.dir,U=b.date,ee={crc32:0,compressedSize:0,uncompressedSize:0};m&&!u||(ee.crc32=g.crc32,ee.compressedSize=g.compressedSize,ee.uncompressedSize=g.uncompressedSize);var z=0;m&&(z|=8),T||!W&&!_||(z|=2048);var F=0,A=0;H&&(F|=16),c==="UNIX"?(A=798,F|=function(D,le){var de=D;return D||(de=le?16893:33204),(65535&de)<<16}(b.unixPermissions,H)):(A=20,F|=function(D){return 63&(D||0)}(b.dosPermissions)),w=U.getUTCHours(),w<<=6,w|=U.getUTCMinutes(),w<<=5,w|=U.getUTCSeconds()/2,k=U.getUTCFullYear()-1980,k<<=4,k|=U.getUTCMonth()+1,k<<=5,k|=U.getUTCDate(),W&&(ce=s(1,1)+s(p(P),4)+O,V+="up"+s(ce.length,2)+ce),_&&(Q=s(1,1)+s(p(J),4)+R,V+="uc"+s(Q.length,2)+Q);var B="";return B+=` -\0`,B+=s(z,2),B+=N.magic,B+=s(w,2),B+=s(k,2),B+=s(ee.crc32,4),B+=s(ee.compressedSize,4),B+=s(ee.uncompressedSize,4),B+=s(P.length,2),B+=s(V.length,2),{fileRecord:y.LOCAL_FILE_HEADER+B+P+V,dirRecord:y.CENTRAL_FILE_HEADER+s(A,2)+B+s(J.length,2)+"\0\0\0\0"+s(F,4)+s(v,4)+P+V+J}}var a=n("../utils"),l=n("../stream/GenericWorker"),d=n("../utf8"),p=n("../crc32"),y=n("../signature");function x(g,m,u,v){l.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=m,this.zipPlatform=u,this.encodeFileName=v,this.streamFiles=g,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}a.inherits(x,l),x.prototype.push=function(g){var m=g.meta.percent||0,u=this.entriesCount,v=this._sources.length;this.accumulate?this.contentBuffer.push(g):(this.bytesWritten+=g.data.length,l.prototype.push.call(this,{data:g.data,meta:{currentFile:this.currentFile,percent:u?(m+100*(u-v-1))/u:100}}))},x.prototype.openedSource=function(g){this.currentSourceOffset=this.bytesWritten,this.currentFile=g.file.name;var m=this.streamFiles&&!g.file.dir;if(m){var u=o(g,m,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:u.fileRecord,meta:{percent:0}})}else this.accumulate=!0},x.prototype.closedSource=function(g){this.accumulate=!1;var m=this.streamFiles&&!g.file.dir,u=o(g,m,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(u.dirRecord),m)this.push({data:function(v){return y.DATA_DESCRIPTOR+s(v.crc32,4)+s(v.compressedSize,4)+s(v.uncompressedSize,4)}(g),meta:{percent:100}});else for(this.push({data:u.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},x.prototype.flush=function(){for(var g=this.bytesWritten,m=0;m=this.index;l--)d=(d<<8)+this.byteAt(l);return this.index+=a,d},readString:function(a){return s.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date(Date.UTC(1980+(a>>25&127),(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1))}},r.exports=o},{"../utils":32}],19:[function(n,r,i){var s=n("./Uint8ArrayReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.readData=function(a){this.checkOffset(a);var l=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},r.exports=o},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,r,i){var s=n("./DataReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.byteAt=function(a){return this.data.charCodeAt(this.zero+a)},o.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)-this.zero},o.prototype.readAndCheckSignature=function(a){return a===this.readData(4)},o.prototype.readData=function(a){this.checkOffset(a);var l=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},r.exports=o},{"../utils":32,"./DataReader":18}],21:[function(n,r,i){var s=n("./ArrayReader");function o(a){s.call(this,a)}n("../utils").inherits(o,s),o.prototype.readData=function(a){if(this.checkOffset(a),a===0)return new Uint8Array(0);var l=this.data.subarray(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},r.exports=o},{"../utils":32,"./ArrayReader":17}],22:[function(n,r,i){var s=n("../utils"),o=n("../support"),a=n("./ArrayReader"),l=n("./StringReader"),d=n("./NodeBufferReader"),p=n("./Uint8ArrayReader");r.exports=function(y){var x=s.getTypeOf(y);return s.checkSupport(x),x!=="string"||o.uint8array?x==="nodebuffer"?new d(y):o.uint8array?new p(s.transformTo("uint8array",y)):new a(s.transformTo("array",y)):new l(y)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,r,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,r,i){var s=n("./GenericWorker"),o=n("../utils");function a(l){s.call(this,"ConvertWorker to "+l),this.destType=l}o.inherits(a,s),a.prototype.processChunk=function(l){this.push({data:o.transformTo(this.destType,l.data),meta:l.meta})},r.exports=a},{"../utils":32,"./GenericWorker":28}],25:[function(n,r,i){var s=n("./GenericWorker"),o=n("../crc32");function a(){s.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(a,s),a.prototype.processChunk=function(l){this.streamInfo.crc32=o(l.data,this.streamInfo.crc32||0),this.push(l)},r.exports=a},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,r,i){var s=n("../utils"),o=n("./GenericWorker");function a(l){o.call(this,"DataLengthProbe for "+l),this.propName=l,this.withStreamInfo(l,0)}s.inherits(a,o),a.prototype.processChunk=function(l){if(l){var d=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=d+l.data.length}o.prototype.processChunk.call(this,l)},r.exports=a},{"../utils":32,"./GenericWorker":28}],27:[function(n,r,i){var s=n("../utils"),o=n("./GenericWorker");function a(l){o.call(this,"DataWorker");var d=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,l.then(function(p){d.dataIsReady=!0,d.data=p,d.max=p&&p.length||0,d.type=s.getTypeOf(p),d.isPaused||d._tickAndRepeat()},function(p){d.error(p)})}s.inherits(a,o),a.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this.data=null},a.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,s.delay(this._tickAndRepeat,[],this)),!0)},a.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(s.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},a.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var l=null,d=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":l=this.data.substring(this.index,d);break;case"uint8array":l=this.data.subarray(this.index,d);break;case"array":case"nodebuffer":l=this.data.slice(this.index,d)}return this.index=d,this.push({data:l,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=a},{"../utils":32,"./GenericWorker":28}],28:[function(n,r,i){function s(o){this.name=o||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}s.prototype={push:function(o){this.emit("data",o)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(o){this.emit("error",o)}return!0},error:function(o){return!this.isFinished&&(this.isPaused?this.generatedError=o:(this.isFinished=!0,this.emit("error",o),this.previous&&this.previous.error(o),this.cleanUp()),!0)},on:function(o,a){return this._listeners[o].push(a),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(o,a){if(this._listeners[o])for(var l=0;l "+o:o}},r.exports=s},{}],29:[function(n,r,i){var s=n("../utils"),o=n("./ConvertWorker"),a=n("./GenericWorker"),l=n("../base64"),d=n("../support"),p=n("../external"),y=null;if(d.nodestream)try{y=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function x(m,u){return new p.Promise(function(v,c){var h=[],w=m._internalType,k=m._outputType,b=m._mimeType;m.on("data",function(N,T){h.push(N),u&&u(T)}).on("error",function(N){h=[],c(N)}).on("end",function(){try{var N=function(T,P,O){switch(T){case"blob":return s.newBlob(s.transformTo("arraybuffer",P),O);case"base64":return l.encode(P);default:return s.transformTo(T,P)}}(k,function(T,P){var O,M=0,J=null,R=0;for(O=0;O"u")i.blob=!1;else{var s=new ArrayBuffer(0);try{i.blob=new Blob([s],{type:"application/zip"}).size===0}catch{try{var o=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);o.append(s),i.blob=o.getBlob("application/zip").size===0}catch{i.blob=!1}}}try{i.nodestream=!!n("readable-stream").Readable}catch{i.nodestream=!1}},{"readable-stream":16}],31:[function(n,r,i){for(var s=n("./utils"),o=n("./support"),a=n("./nodejsUtils"),l=n("./stream/GenericWorker"),d=new Array(256),p=0;p<256;p++)d[p]=252<=p?6:248<=p?5:240<=p?4:224<=p?3:192<=p?2:1;d[254]=d[254]=1;function y(){l.call(this,"utf-8 decode"),this.leftOver=null}function x(){l.call(this,"utf-8 encode")}i.utf8encode=function(g){return o.nodebuffer?a.newBufferFrom(g,"utf-8"):function(m){var u,v,c,h,w,k=m.length,b=0;for(h=0;h>>6:(v<65536?u[w++]=224|v>>>12:(u[w++]=240|v>>>18,u[w++]=128|v>>>12&63),u[w++]=128|v>>>6&63),u[w++]=128|63&v);return u}(g)},i.utf8decode=function(g){return o.nodebuffer?s.transformTo("nodebuffer",g).toString("utf-8"):function(m){var u,v,c,h,w=m.length,k=new Array(2*w);for(u=v=0;u>10&1023,k[v++]=56320|1023&c)}return k.length!==v&&(k.subarray?k=k.subarray(0,v):k.length=v),s.applyFromCharCode(k)}(g=s.transformTo(o.uint8array?"uint8array":"array",g))},s.inherits(y,l),y.prototype.processChunk=function(g){var m=s.transformTo(o.uint8array?"uint8array":"array",g.data);if(this.leftOver&&this.leftOver.length){if(o.uint8array){var u=m;(m=new Uint8Array(u.length+this.leftOver.length)).set(this.leftOver,0),m.set(u,this.leftOver.length)}else m=this.leftOver.concat(m);this.leftOver=null}var v=function(h,w){var k;for((w=w||h.length)>h.length&&(w=h.length),k=w-1;0<=k&&(192&h[k])==128;)k--;return k<0||k===0?w:k+d[h[k]]>w?k:w}(m),c=m;v!==m.length&&(o.uint8array?(c=m.subarray(0,v),this.leftOver=m.subarray(v,m.length)):(c=m.slice(0,v),this.leftOver=m.slice(v,m.length))),this.push({data:i.utf8decode(c),meta:g.meta})},y.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=y,s.inherits(x,l),x.prototype.processChunk=function(g){this.push({data:i.utf8encode(g.data),meta:g.meta})},i.Utf8EncodeWorker=x},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,r,i){var s=n("./support"),o=n("./base64"),a=n("./nodejsUtils"),l=n("./external");function d(u){return u}function p(u,v){for(var c=0;c>8;this.dir=!!(16&this.externalFileAttributes),g==0&&(this.dosPermissions=63&this.externalFileAttributes),g==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var g=s(this.extraFields[1].value);this.uncompressedSize===o.MAX_VALUE_32BITS&&(this.uncompressedSize=g.readInt(8)),this.compressedSize===o.MAX_VALUE_32BITS&&(this.compressedSize=g.readInt(8)),this.localHeaderOffset===o.MAX_VALUE_32BITS&&(this.localHeaderOffset=g.readInt(8)),this.diskNumberStart===o.MAX_VALUE_32BITS&&(this.diskNumberStart=g.readInt(4))}},readExtraFields:function(g){var m,u,v,c=g.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});g.index+4>>6:(g<65536?x[v++]=224|g>>>12:(x[v++]=240|g>>>18,x[v++]=128|g>>>12&63),x[v++]=128|g>>>6&63),x[v++]=128|63&g);return x},i.buf2binstring=function(y){return p(y,y.length)},i.binstring2buf=function(y){for(var x=new s.Buf8(y.length),g=0,m=x.length;g>10&1023,h[m++]=56320|1023&u)}return p(h,m)},i.utf8border=function(y,x){var g;for((x=x||y.length)>y.length&&(x=y.length),g=x-1;0<=g&&(192&y[g])==128;)g--;return g<0||g===0?x:g+l[y[g]]>x?g:x}},{"./common":41}],43:[function(n,r,i){r.exports=function(s,o,a,l){for(var d=65535&s|0,p=s>>>16&65535|0,y=0;a!==0;){for(a-=y=2e3>>1:o>>>1;a[l]=o}return a}();r.exports=function(o,a,l,d){var p=s,y=d+l;o^=-1;for(var x=d;x>>8^p[255&(o^a[x])];return-1^o}},{}],46:[function(n,r,i){var s,o=n("../utils/common"),a=n("./trees"),l=n("./adler32"),d=n("./crc32"),p=n("./messages"),y=0,x=4,g=0,m=-2,u=-1,v=4,c=2,h=8,w=9,k=286,b=30,N=19,T=2*k+1,P=15,O=3,M=258,J=M+O+1,R=42,W=113,_=1,V=2,ce=3,Q=4;function H(f,I){return f.msg=p[I],I}function U(f){return(f<<1)-(4f.avail_out&&(L=f.avail_out),L!==0&&(o.arraySet(f.output,I.pending_buf,I.pending_out,L,f.next_out),f.next_out+=L,I.pending_out+=L,f.total_out+=L,f.avail_out-=L,I.pending-=L,I.pending===0&&(I.pending_out=0))}function F(f,I){a._tr_flush_block(f,0<=f.block_start?f.block_start:-1,f.strstart-f.block_start,I),f.block_start=f.strstart,z(f.strm)}function A(f,I){f.pending_buf[f.pending++]=I}function B(f,I){f.pending_buf[f.pending++]=I>>>8&255,f.pending_buf[f.pending++]=255&I}function D(f,I){var L,C,E=f.max_chain_length,j=f.strstart,Y=f.prev_length,G=f.nice_match,$=f.strstart>f.w_size-J?f.strstart-(f.w_size-J):0,ie=f.window,fe=f.w_mask,oe=f.prev,pe=f.strstart+M,ve=ie[j+Y-1],ye=ie[j+Y];f.prev_length>=f.good_match&&(E>>=2),G>f.lookahead&&(G=f.lookahead);do if(ie[(L=I)+Y]===ye&&ie[L+Y-1]===ve&&ie[L]===ie[j]&&ie[++L]===ie[j+1]){j+=2,L++;do;while(ie[++j]===ie[++L]&&ie[++j]===ie[++L]&&ie[++j]===ie[++L]&&ie[++j]===ie[++L]&&ie[++j]===ie[++L]&&ie[++j]===ie[++L]&&ie[++j]===ie[++L]&&ie[++j]===ie[++L]&&j$&&--E!=0);return Y<=f.lookahead?Y:f.lookahead}function le(f){var I,L,C,E,j,Y,G,$,ie,fe,oe=f.w_size;do{if(E=f.window_size-f.lookahead-f.strstart,f.strstart>=oe+(oe-J)){for(o.arraySet(f.window,f.window,oe,oe,0),f.match_start-=oe,f.strstart-=oe,f.block_start-=oe,I=L=f.hash_size;C=f.head[--I],f.head[I]=oe<=C?C-oe:0,--L;);for(I=L=oe;C=f.prev[--I],f.prev[I]=oe<=C?C-oe:0,--L;);E+=oe}if(f.strm.avail_in===0)break;if(Y=f.strm,G=f.window,$=f.strstart+f.lookahead,ie=E,fe=void 0,fe=Y.avail_in,ie=O)for(j=f.strstart-f.insert,f.ins_h=f.window[j],f.ins_h=(f.ins_h<=O&&(f.ins_h=(f.ins_h<=O)if(C=a._tr_tally(f,f.strstart-f.match_start,f.match_length-O),f.lookahead-=f.match_length,f.match_length<=f.max_lazy_match&&f.lookahead>=O){for(f.match_length--;f.strstart++,f.ins_h=(f.ins_h<=O&&(f.ins_h=(f.ins_h<=O&&f.match_length<=f.prev_length){for(E=f.strstart+f.lookahead-O,C=a._tr_tally(f,f.strstart-1-f.prev_match,f.prev_length-O),f.lookahead-=f.prev_length-1,f.prev_length-=2;++f.strstart<=E&&(f.ins_h=(f.ins_h<f.pending_buf_size-5&&(L=f.pending_buf_size-5);;){if(f.lookahead<=1){if(le(f),f.lookahead===0&&I===y)return _;if(f.lookahead===0)break}f.strstart+=f.lookahead,f.lookahead=0;var C=f.block_start+L;if((f.strstart===0||f.strstart>=C)&&(f.lookahead=f.strstart-C,f.strstart=C,F(f,!1),f.strm.avail_out===0)||f.strstart-f.block_start>=f.w_size-J&&(F(f,!1),f.strm.avail_out===0))return _}return f.insert=0,I===x?(F(f,!0),f.strm.avail_out===0?ce:Q):(f.strstart>f.block_start&&(F(f,!1),f.strm.avail_out),_)}),new se(4,4,8,4,de),new se(4,5,16,8,de),new se(4,6,32,32,de),new se(4,4,16,16,ue),new se(8,16,32,32,ue),new se(8,16,128,128,ue),new se(8,32,128,256,ue),new se(32,128,258,1024,ue),new se(32,258,258,4096,ue)],i.deflateInit=function(f,I){return ne(f,I,h,15,8,0)},i.deflateInit2=ne,i.deflateReset=q,i.deflateResetKeep=re,i.deflateSetHeader=function(f,I){return f&&f.state?f.state.wrap!==2?m:(f.state.gzhead=I,g):m},i.deflate=function(f,I){var L,C,E,j;if(!f||!f.state||5>8&255),A(C,C.gzhead.time>>16&255),A(C,C.gzhead.time>>24&255),A(C,C.level===9?2:2<=C.strategy||C.level<2?4:0),A(C,255&C.gzhead.os),C.gzhead.extra&&C.gzhead.extra.length&&(A(C,255&C.gzhead.extra.length),A(C,C.gzhead.extra.length>>8&255)),C.gzhead.hcrc&&(f.adler=d(f.adler,C.pending_buf,C.pending,0)),C.gzindex=0,C.status=69):(A(C,0),A(C,0),A(C,0),A(C,0),A(C,0),A(C,C.level===9?2:2<=C.strategy||C.level<2?4:0),A(C,3),C.status=W);else{var Y=h+(C.w_bits-8<<4)<<8;Y|=(2<=C.strategy||C.level<2?0:C.level<6?1:C.level===6?2:3)<<6,C.strstart!==0&&(Y|=32),Y+=31-Y%31,C.status=W,B(C,Y),C.strstart!==0&&(B(C,f.adler>>>16),B(C,65535&f.adler)),f.adler=1}if(C.status===69)if(C.gzhead.extra){for(E=C.pending;C.gzindex<(65535&C.gzhead.extra.length)&&(C.pending!==C.pending_buf_size||(C.gzhead.hcrc&&C.pending>E&&(f.adler=d(f.adler,C.pending_buf,C.pending-E,E)),z(f),E=C.pending,C.pending!==C.pending_buf_size));)A(C,255&C.gzhead.extra[C.gzindex]),C.gzindex++;C.gzhead.hcrc&&C.pending>E&&(f.adler=d(f.adler,C.pending_buf,C.pending-E,E)),C.gzindex===C.gzhead.extra.length&&(C.gzindex=0,C.status=73)}else C.status=73;if(C.status===73)if(C.gzhead.name){E=C.pending;do{if(C.pending===C.pending_buf_size&&(C.gzhead.hcrc&&C.pending>E&&(f.adler=d(f.adler,C.pending_buf,C.pending-E,E)),z(f),E=C.pending,C.pending===C.pending_buf_size)){j=1;break}j=C.gzindexE&&(f.adler=d(f.adler,C.pending_buf,C.pending-E,E)),j===0&&(C.gzindex=0,C.status=91)}else C.status=91;if(C.status===91)if(C.gzhead.comment){E=C.pending;do{if(C.pending===C.pending_buf_size&&(C.gzhead.hcrc&&C.pending>E&&(f.adler=d(f.adler,C.pending_buf,C.pending-E,E)),z(f),E=C.pending,C.pending===C.pending_buf_size)){j=1;break}j=C.gzindexE&&(f.adler=d(f.adler,C.pending_buf,C.pending-E,E)),j===0&&(C.status=103)}else C.status=103;if(C.status===103&&(C.gzhead.hcrc?(C.pending+2>C.pending_buf_size&&z(f),C.pending+2<=C.pending_buf_size&&(A(C,255&f.adler),A(C,f.adler>>8&255),f.adler=0,C.status=W)):C.status=W),C.pending!==0){if(z(f),f.avail_out===0)return C.last_flush=-1,g}else if(f.avail_in===0&&U(I)<=U(L)&&I!==x)return H(f,-5);if(C.status===666&&f.avail_in!==0)return H(f,-5);if(f.avail_in!==0||C.lookahead!==0||I!==y&&C.status!==666){var G=C.strategy===2?function($,ie){for(var fe;;){if($.lookahead===0&&(le($),$.lookahead===0)){if(ie===y)return _;break}if($.match_length=0,fe=a._tr_tally($,0,$.window[$.strstart]),$.lookahead--,$.strstart++,fe&&(F($,!1),$.strm.avail_out===0))return _}return $.insert=0,ie===x?(F($,!0),$.strm.avail_out===0?ce:Q):$.last_lit&&(F($,!1),$.strm.avail_out===0)?_:V}(C,I):C.strategy===3?function($,ie){for(var fe,oe,pe,ve,ye=$.window;;){if($.lookahead<=M){if(le($),$.lookahead<=M&&ie===y)return _;if($.lookahead===0)break}if($.match_length=0,$.lookahead>=O&&0<$.strstart&&(oe=ye[pe=$.strstart-1])===ye[++pe]&&oe===ye[++pe]&&oe===ye[++pe]){ve=$.strstart+M;do;while(oe===ye[++pe]&&oe===ye[++pe]&&oe===ye[++pe]&&oe===ye[++pe]&&oe===ye[++pe]&&oe===ye[++pe]&&oe===ye[++pe]&&oe===ye[++pe]&&pe$.lookahead&&($.match_length=$.lookahead)}if($.match_length>=O?(fe=a._tr_tally($,1,$.match_length-O),$.lookahead-=$.match_length,$.strstart+=$.match_length,$.match_length=0):(fe=a._tr_tally($,0,$.window[$.strstart]),$.lookahead--,$.strstart++),fe&&(F($,!1),$.strm.avail_out===0))return _}return $.insert=0,ie===x?(F($,!0),$.strm.avail_out===0?ce:Q):$.last_lit&&(F($,!1),$.strm.avail_out===0)?_:V}(C,I):s[C.level].func(C,I);if(G!==ce&&G!==Q||(C.status=666),G===_||G===ce)return f.avail_out===0&&(C.last_flush=-1),g;if(G===V&&(I===1?a._tr_align(C):I!==5&&(a._tr_stored_block(C,0,0,!1),I===3&&(ee(C.head),C.lookahead===0&&(C.strstart=0,C.block_start=0,C.insert=0))),z(f),f.avail_out===0))return C.last_flush=-1,g}return I!==x?g:C.wrap<=0?1:(C.wrap===2?(A(C,255&f.adler),A(C,f.adler>>8&255),A(C,f.adler>>16&255),A(C,f.adler>>24&255),A(C,255&f.total_in),A(C,f.total_in>>8&255),A(C,f.total_in>>16&255),A(C,f.total_in>>24&255)):(B(C,f.adler>>>16),B(C,65535&f.adler)),z(f),0=L.w_size&&(j===0&&(ee(L.head),L.strstart=0,L.block_start=0,L.insert=0),ie=new o.Buf8(L.w_size),o.arraySet(ie,I,fe-L.w_size,L.w_size,0),I=ie,fe=L.w_size),Y=f.avail_in,G=f.next_in,$=f.input,f.avail_in=fe,f.next_in=0,f.input=I,le(L);L.lookahead>=O;){for(C=L.strstart,E=L.lookahead-(O-1);L.ins_h=(L.ins_h<>>=O=P>>>24,w-=O,(O=P>>>16&255)===0)V[p++]=65535&P;else{if(!(16&O)){if(!(64&O)){P=k[(65535&P)+(h&(1<>>=O,w-=O),w<15&&(h+=_[l++]<>>=O=P>>>24,w-=O,!(16&(O=P>>>16&255))){if(!(64&O)){P=b[(65535&P)+(h&(1<>>=O,w-=O,(O=p-y)>3,h&=(1<<(w-=M<<3))-1,s.next_in=l,s.next_out=p,s.avail_in=l>>24&255)+(R>>>8&65280)+((65280&R)<<8)+((255&R)<<24)}function h(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function w(R){var W;return R&&R.state?(W=R.state,R.total_in=R.total_out=W.total=0,R.msg="",W.wrap&&(R.adler=1&W.wrap),W.mode=m,W.last=0,W.havedict=0,W.dmax=32768,W.head=null,W.hold=0,W.bits=0,W.lencode=W.lendyn=new s.Buf32(u),W.distcode=W.distdyn=new s.Buf32(v),W.sane=1,W.back=-1,x):g}function k(R){var W;return R&&R.state?((W=R.state).wsize=0,W.whave=0,W.wnext=0,w(R)):g}function b(R,W){var _,V;return R&&R.state?(V=R.state,W<0?(_=0,W=-W):(_=1+(W>>4),W<48&&(W&=15)),W&&(W<8||15=Q.wsize?(s.arraySet(Q.window,W,_-Q.wsize,Q.wsize,0),Q.wnext=0,Q.whave=Q.wsize):(V<(ce=Q.wsize-Q.wnext)&&(ce=V),s.arraySet(Q.window,W,_-V,ce,Q.wnext),(V-=ce)?(s.arraySet(Q.window,W,_-V,V,0),Q.wnext=V,Q.whave=Q.wsize):(Q.wnext+=ce,Q.wnext===Q.wsize&&(Q.wnext=0),Q.whave>>8&255,_.check=a(_.check,j,2,0),F=z=0,_.mode=2;break}if(_.flags=0,_.head&&(_.head.done=!1),!(1&_.wrap)||(((255&z)<<8)+(z>>8))%31){R.msg="incorrect header check",_.mode=30;break}if((15&z)!=8){R.msg="unknown compression method",_.mode=30;break}if(F-=4,f=8+(15&(z>>>=4)),_.wbits===0)_.wbits=f;else if(f>_.wbits){R.msg="invalid window size",_.mode=30;break}_.dmax=1<>8&1),512&_.flags&&(j[0]=255&z,j[1]=z>>>8&255,_.check=a(_.check,j,2,0)),F=z=0,_.mode=3;case 3:for(;F<32;){if(U===0)break e;U--,z+=V[Q++]<>>8&255,j[2]=z>>>16&255,j[3]=z>>>24&255,_.check=a(_.check,j,4,0)),F=z=0,_.mode=4;case 4:for(;F<16;){if(U===0)break e;U--,z+=V[Q++]<>8),512&_.flags&&(j[0]=255&z,j[1]=z>>>8&255,_.check=a(_.check,j,2,0)),F=z=0,_.mode=5;case 5:if(1024&_.flags){for(;F<16;){if(U===0)break e;U--,z+=V[Q++]<>>8&255,_.check=a(_.check,j,2,0)),F=z=0}else _.head&&(_.head.extra=null);_.mode=6;case 6:if(1024&_.flags&&(U<(D=_.length)&&(D=U),D&&(_.head&&(f=_.head.extra_len-_.length,_.head.extra||(_.head.extra=new Array(_.head.extra_len)),s.arraySet(_.head.extra,V,Q,D,f)),512&_.flags&&(_.check=a(_.check,V,D,Q)),U-=D,Q+=D,_.length-=D),_.length))break e;_.length=0,_.mode=7;case 7:if(2048&_.flags){if(U===0)break e;for(D=0;f=V[Q+D++],_.head&&f&&_.length<65536&&(_.head.name+=String.fromCharCode(f)),f&&D>9&1,_.head.done=!0),R.adler=_.check=0,_.mode=12;break;case 10:for(;F<32;){if(U===0)break e;U--,z+=V[Q++]<>>=7&F,F-=7&F,_.mode=27;break}for(;F<3;){if(U===0)break e;U--,z+=V[Q++]<>>=1)){case 0:_.mode=14;break;case 1:if(M(_),_.mode=20,W!==6)break;z>>>=2,F-=2;break e;case 2:_.mode=17;break;case 3:R.msg="invalid block type",_.mode=30}z>>>=2,F-=2;break;case 14:for(z>>>=7&F,F-=7&F;F<32;){if(U===0)break e;U--,z+=V[Q++]<>>16^65535)){R.msg="invalid stored block lengths",_.mode=30;break}if(_.length=65535&z,F=z=0,_.mode=15,W===6)break e;case 15:_.mode=16;case 16:if(D=_.length){if(U>>=5,F-=5,_.ndist=1+(31&z),z>>>=5,F-=5,_.ncode=4+(15&z),z>>>=4,F-=4,286<_.nlen||30<_.ndist){R.msg="too many length or distance symbols",_.mode=30;break}_.have=0,_.mode=18;case 18:for(;_.have<_.ncode;){for(;F<3;){if(U===0)break e;U--,z+=V[Q++]<>>=3,F-=3}for(;_.have<19;)_.lens[Y[_.have++]]=0;if(_.lencode=_.lendyn,_.lenbits=7,L={bits:_.lenbits},I=d(0,_.lens,0,19,_.lencode,0,_.work,L),_.lenbits=L.bits,I){R.msg="invalid code lengths set",_.mode=30;break}_.have=0,_.mode=19;case 19:for(;_.have<_.nlen+_.ndist;){for(;se=(E=_.lencode[z&(1<<_.lenbits)-1])>>>16&255,X=65535&E,!((ue=E>>>24)<=F);){if(U===0)break e;U--,z+=V[Q++]<>>=ue,F-=ue,_.lens[_.have++]=X;else{if(X===16){for(C=ue+2;F>>=ue,F-=ue,_.have===0){R.msg="invalid bit length repeat",_.mode=30;break}f=_.lens[_.have-1],D=3+(3&z),z>>>=2,F-=2}else if(X===17){for(C=ue+3;F>>=ue)),z>>>=3,F-=3}else{for(C=ue+7;F>>=ue)),z>>>=7,F-=7}if(_.have+D>_.nlen+_.ndist){R.msg="invalid bit length repeat",_.mode=30;break}for(;D--;)_.lens[_.have++]=f}}if(_.mode===30)break;if(_.lens[256]===0){R.msg="invalid code -- missing end-of-block",_.mode=30;break}if(_.lenbits=9,L={bits:_.lenbits},I=d(p,_.lens,0,_.nlen,_.lencode,0,_.work,L),_.lenbits=L.bits,I){R.msg="invalid literal/lengths set",_.mode=30;break}if(_.distbits=6,_.distcode=_.distdyn,L={bits:_.distbits},I=d(y,_.lens,_.nlen,_.ndist,_.distcode,0,_.work,L),_.distbits=L.bits,I){R.msg="invalid distances set",_.mode=30;break}if(_.mode=20,W===6)break e;case 20:_.mode=21;case 21:if(6<=U&&258<=ee){R.next_out=H,R.avail_out=ee,R.next_in=Q,R.avail_in=U,_.hold=z,_.bits=F,l(R,B),H=R.next_out,ce=R.output,ee=R.avail_out,Q=R.next_in,V=R.input,U=R.avail_in,z=_.hold,F=_.bits,_.mode===12&&(_.back=-1);break}for(_.back=0;se=(E=_.lencode[z&(1<<_.lenbits)-1])>>>16&255,X=65535&E,!((ue=E>>>24)<=F);){if(U===0)break e;U--,z+=V[Q++]<>re)])>>>16&255,X=65535&E,!(re+(ue=E>>>24)<=F);){if(U===0)break e;U--,z+=V[Q++]<>>=re,F-=re,_.back+=re}if(z>>>=ue,F-=ue,_.back+=ue,_.length=X,se===0){_.mode=26;break}if(32&se){_.back=-1,_.mode=12;break}if(64&se){R.msg="invalid literal/length code",_.mode=30;break}_.extra=15&se,_.mode=22;case 22:if(_.extra){for(C=_.extra;F>>=_.extra,F-=_.extra,_.back+=_.extra}_.was=_.length,_.mode=23;case 23:for(;se=(E=_.distcode[z&(1<<_.distbits)-1])>>>16&255,X=65535&E,!((ue=E>>>24)<=F);){if(U===0)break e;U--,z+=V[Q++]<>re)])>>>16&255,X=65535&E,!(re+(ue=E>>>24)<=F);){if(U===0)break e;U--,z+=V[Q++]<>>=re,F-=re,_.back+=re}if(z>>>=ue,F-=ue,_.back+=ue,64&se){R.msg="invalid distance code",_.mode=30;break}_.offset=X,_.extra=15&se,_.mode=24;case 24:if(_.extra){for(C=_.extra;F>>=_.extra,F-=_.extra,_.back+=_.extra}if(_.offset>_.dmax){R.msg="invalid distance too far back",_.mode=30;break}_.mode=25;case 25:if(ee===0)break e;if(D=B-ee,_.offset>D){if((D=_.offset-D)>_.whave&&_.sane){R.msg="invalid distance too far back",_.mode=30;break}le=D>_.wnext?(D-=_.wnext,_.wsize-D):_.wnext-D,D>_.length&&(D=_.length),de=_.window}else de=ce,le=H-_.offset,D=_.length;for(eeT?(O=le[de+v[W]],F[A+v[W]]):(O=96,0),h=1<>H)+(w-=h)]=P<<24|O<<16|M|0,w!==0;);for(h=1<>=1;if(h!==0?(z&=h-1,z+=h):z=0,W++,--B[R]==0){if(R===V)break;R=y[x+v[W]]}if(ce>>7)]}function A(E,j){E.pending_buf[E.pending++]=255&j,E.pending_buf[E.pending++]=j>>>8&255}function B(E,j,Y){E.bi_valid>c-Y?(E.bi_buf|=j<>c-E.bi_valid,E.bi_valid+=Y-c):(E.bi_buf|=j<>>=1,Y<<=1,0<--j;);return Y>>>1}function de(E,j,Y){var G,$,ie=new Array(v+1),fe=0;for(G=1;G<=v;G++)ie[G]=fe=fe+Y[G-1]<<1;for($=0;$<=j;$++){var oe=E[2*$+1];oe!==0&&(E[2*$]=le(ie[oe]++,oe))}}function ue(E){var j;for(j=0;j>1;1<=Y;Y--)re(E,ie,Y);for($=pe;Y=E.heap[1],E.heap[1]=E.heap[E.heap_len--],re(E,ie,1),G=E.heap[1],E.heap[--E.heap_max]=Y,E.heap[--E.heap_max]=G,ie[2*$]=ie[2*Y]+ie[2*G],E.depth[$]=(E.depth[Y]>=E.depth[G]?E.depth[Y]:E.depth[G])+1,ie[2*Y+1]=ie[2*G+1]=$,E.heap[1]=$++,re(E,ie,1),2<=E.heap_len;);E.heap[--E.heap_max]=E.heap[1],function(ye,We){var Jt,at,en,be,pn,tn,tt=We.dyn_tree,Pn=We.max_code,jr=We.stat_desc.static_tree,Tt=We.stat_desc.has_stree,_e=We.stat_desc.extra_bits,Te=We.stat_desc.extra_base,Ae=We.stat_desc.max_length,je=0;for(be=0;be<=v;be++)ye.bl_count[be]=0;for(tt[2*ye.heap[ye.heap_max]+1]=0,Jt=ye.heap_max+1;Jt>=7;$>>=1)if(1&ve&&oe.dyn_ltree[2*pe]!==0)return o;if(oe.dyn_ltree[18]!==0||oe.dyn_ltree[20]!==0||oe.dyn_ltree[26]!==0)return a;for(pe=32;pe>>3,(ie=E.static_len+3+7>>>3)<=$&&($=ie)):$=ie=Y+5,Y+4<=$&&j!==-1?C(E,j,Y,G):E.strategy===4||ie===$?(B(E,2+(G?1:0),3),q(E,J,R)):(B(E,4+(G?1:0),3),function(oe,pe,ve,ye){var We;for(B(oe,pe-257,5),B(oe,ve-1,5),B(oe,ye-4,4),We=0;We>>8&255,E.pending_buf[E.d_buf+2*E.last_lit+1]=255&j,E.pending_buf[E.l_buf+E.last_lit]=255&Y,E.last_lit++,j===0?E.dyn_ltree[2*Y]++:(E.matches++,j--,E.dyn_ltree[2*(_[Y]+y+1)]++,E.dyn_dtree[2*F(j)]++),E.last_lit===E.lit_bufsize-1},i._tr_align=function(E){B(E,2,3),D(E,w,J),function(j){j.bi_valid===16?(A(j,j.bi_buf),j.bi_buf=0,j.bi_valid=0):8<=j.bi_valid&&(j.pending_buf[j.pending++]=255&j.bi_buf,j.bi_buf>>=8,j.bi_valid-=8)}(E)}},{"../utils/common":41}],53:[function(n,r,i){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,r,i){(function(s){(function(o,a){if(!o.setImmediate){var l,d,p,y,x=1,g={},m=!1,u=o.document,v=Object.getPrototypeOf&&Object.getPrototypeOf(o);v=v&&v.setTimeout?v:o,l={}.toString.call(o.process)==="[object process]"?function(k){process.nextTick(function(){h(k)})}:function(){if(o.postMessage&&!o.importScripts){var k=!0,b=o.onmessage;return o.onmessage=function(){k=!1},o.postMessage("","*"),o.onmessage=b,k}}()?(y="setImmediate$"+Math.random()+"$",o.addEventListener?o.addEventListener("message",w,!1):o.attachEvent("onmessage",w),function(k){o.postMessage(y+k,"*")}):o.MessageChannel?((p=new MessageChannel).port1.onmessage=function(k){h(k.data)},function(k){p.port2.postMessage(k)}):u&&"onreadystatechange"in u.createElement("script")?(d=u.documentElement,function(k){var b=u.createElement("script");b.onreadystatechange=function(){h(k),b.onreadystatechange=null,d.removeChild(b),b=null},d.appendChild(b)}):function(k){setTimeout(h,0,k)},v.setImmediate=function(k){typeof k!="function"&&(k=new Function(""+k));for(var b=new Array(arguments.length-1),N=0;N"u"?s===void 0?this:s:self)}).call(this,typeof Es<"u"?Es:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(_m);var Xw=_m.exports;const hf=su(Xw);function pf(){const{selectedImage:e,selectedImages:t,currentLibraryId:n,selectedFolder:r,images:i,setMobileView:s,isResizingPanels:o,resizingSide:a}=me(),[l,d]=Z.useState(!1),[p,y]=Z.useState(""),[x,g]=Z.useState(!1),[m,u]=Z.useState(!1),[v,c]=Z.useState(!1),[h,w]=Z.useState(0),[k,b]=Z.useState(!1),[N,T]=Z.useState(0),P=t.length>0,O=P?t[0]:e;if(Z.useEffect(()=>{const A=()=>{d(window.innerWidth<768)};return A(),window.addEventListener("resize",A),()=>window.removeEventListener("resize",A)},[]),Z.useEffect(()=>{if(!e||!n){y("");return}const A=M();if(y(A),g(!0),o){g(!1);return}const B=J(),D=new Image;return D.onload=()=>{y(B),g(!1)},D.onerror=()=>{console.error("Failed to load original image"),g(!1)},D.src=B,()=>{D.onload=null,D.onerror=null}},[e,n,o,a]),!e&&t.length===0)return S.jsx("div",{className:"w-full border-l border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 flex items-center justify-center",children:S.jsx("p",{className:"text-gray-400 dark:text-gray-500 text-sm",children:"选择图片查看详情"})});const M=()=>{if(!n||!e.thumbnail_path)return"";const A=e.thumbnail_path.replace(/\\/g,"/").split("/").pop();return Me.getThumbnailUrl(n,"200",A)},J=()=>!n||!e.path?"":Me.getOriginalUrl(n,e.path),R=()=>typeof ClipboardItem<"u"&&navigator.clipboard&&typeof navigator.clipboard.write=="function",W=async A=>new Promise(B=>{const D=document.createElement("div");D.setAttribute("contenteditable","true"),D.style.position="fixed",D.style.left="-9999px",D.style.top="-9999px",D.style.opacity="0",document.body.appendChild(D);const le=document.createElement("img");le.crossOrigin="anonymous",le.onload=()=>{D.appendChild(le);const de=document.createRange();de.selectNodeContents(D);const ue=window.getSelection();ue.removeAllRanges(),ue.addRange(de);let se=!1;try{se=document.execCommand("copy")}catch(X){console.error("execCommand copy 失败:",X)}ue.removeAllRanges(),document.body.removeChild(D),B(se)},le.onerror=()=>{document.body.removeChild(D),B(!1)},le.src=A}),_=async A=>new Promise(async B=>{try{const le=await(await fetch(A)).blob(),de=new Image;de.crossOrigin="anonymous";const ue=new Promise((C,E)=>{de.onload=C,de.onerror=E});de.src=URL.createObjectURL(le),await ue;const se=document.createElement("canvas");se.width=de.width,se.height=de.height,se.getContext("2d").drawImage(de,0,0),URL.revokeObjectURL(de.src);const re=se.toDataURL("image/png"),q=document.createElement("div");q.setAttribute("contenteditable","true"),q.style.position="fixed",q.style.left="-9999px",q.style.top="-9999px",q.style.opacity="0",document.body.appendChild(q);const ne=document.createElement("img");ne.src=re,q.appendChild(ne),await new Promise(C=>setTimeout(C,50));const f=document.createRange();f.selectNodeContents(q);const I=window.getSelection();I.removeAllRanges(),I.addRange(f);let L=!1;try{L=document.execCommand("copy")}catch(C){console.error("execCommand copy 失败:",C)}I.removeAllRanges(),document.body.removeChild(q),B(L)}catch(D){console.error("Canvas 复制失败:",D),B(!1)}}),V=A=>{const B=document.createElement("textarea");B.value=A,B.style.position="fixed",B.style.left="-9999px",B.style.top="-9999px",document.body.appendChild(B),B.focus(),B.select();try{return document.execCommand("copy"),!0}catch(D){return console.error("execCommand 复制失败:",D),!1}finally{document.body.removeChild(B)}},ce=async()=>{try{const A=Me.getOriginalUrl(n,e.path);if(R())try{const ue=await(await fetch(A)).blob(),se=new Image,X=new Promise((I,L)=>{se.onload=I,se.onerror=L});se.src=URL.createObjectURL(ue),await X;const re=document.createElement("canvas");re.width=se.width,re.height=se.height,re.getContext("2d").drawImage(se,0,0),URL.revokeObjectURL(se.src);const ne=await new Promise(I=>{re.toBlob(I,"image/png")}),f=new ClipboardItem({"image/png":ne});await navigator.clipboard.write([f]),u(!0),setTimeout(()=>u(!1),2e3);return}catch(de){console.warn("Clipboard API 失败,尝试备用方案:",de)}if(console.log("尝试 Canvas + execCommand 方案..."),await _(A)){u(!0),setTimeout(()=>u(!1),2e3);return}if(console.log("尝试直接图片 URL 方案..."),await W(A)){u(!0),setTimeout(()=>u(!1),2e3);return}console.warn("所有图片复制方案失败,降级为复制链接"),V(A)?(u(!0),setTimeout(()=>u(!1),2e3),alert(`已复制图片链接到剪贴板 -(当前浏览器环境限制,无法直接复制图片)`)):alert(`复制失败,请手动复制图片链接: -`+A)}catch(A){console.error("复制图片失败:",A),alert("复制图片失败,请重试")}},Q=async A=>new Promise(async B=>{try{const D=document.createElement("div");D.setAttribute("contenteditable","true"),D.style.position="fixed",D.style.left="-9999px",D.style.top="-9999px",D.style.opacity="0",document.body.appendChild(D);for(const{url:se,filename:X}of A)try{const q=await(await fetch(se)).blob(),ne=new Image;ne.crossOrigin="anonymous",await new Promise((E,j)=>{ne.onload=E,ne.onerror=j,ne.src=URL.createObjectURL(q)});const f=document.createElement("canvas");f.width=ne.width,f.height=ne.height,f.getContext("2d").drawImage(ne,0,0),URL.revokeObjectURL(ne.src);const L=f.toDataURL("image/png"),C=document.createElement("img");C.src=L,C.alt=X,C.style.display="block",C.style.marginBottom="10px",D.appendChild(C)}catch(re){console.error(`加载图片失败: ${X}`,re)}await new Promise(se=>setTimeout(se,100));const le=document.createRange();le.selectNodeContents(D);const de=window.getSelection();de.removeAllRanges(),de.addRange(le);let ue=!1;try{ue=document.execCommand("copy")}catch(se){console.error("execCommand copy 失败:",se)}de.removeAllRanges(),document.body.removeChild(D),B(ue)}catch(D){console.error("批量复制图片失败:",D),B(!1)}}),H=async()=>{try{const A=P?t:[e];if(A.length===1){await ce();return}const B=A.map(ue=>({url:Me.getOriginalUrl(n,ue.path),filename:ue.filename})),D=A.map(ue=>ue.filename).join(` -`);if(R())try{const se=(await Promise.all(A.map(async X=>{const re=Me.getOriginalUrl(n,X.path),ne=await(await fetch(re)).blob();return new Promise(f=>{const I=new FileReader;I.onloadend=()=>{f({dataUrl:I.result,filename:X.filename})},I.readAsDataURL(ne)})}))).map(({dataUrl:X,filename:re})=>`${re}`).join(` -`);await navigator.clipboard.write([new ClipboardItem({"text/html":new Blob([se],{type:"text/html"}),"text/plain":new Blob([D],{type:"text/plain"})})]),u(!0),setTimeout(()=>u(!1),2e3);return}catch(ue){console.warn("Clipboard API 失败,尝试备用方案:",ue)}if(console.log("尝试 contenteditable 批量复制方案..."),await Q(B)){u(!0),setTimeout(()=>u(!1),2e3);return}console.warn("批量图片复制失败,降级为复制文件名"),V(D)?(u(!0),setTimeout(()=>u(!1),2e3),alert(`已复制 ${A.length} 个文件名到剪贴板 -(当前环境限制,建议使用"导出"功能)`)):alert('复制失败,请使用"导出"功能下载图片')}catch(A){console.error("复制图片失败:",A),alert("复制图片失败,请重试")}},U=async()=>{c(!0);try{const A=P?t:[e];if(A.length===1){const B=Me.getOriginalUrl(n,A[0].path),D=document.createElement("a");D.href=B,D.download=A[0].filename,D.target="_blank",document.body.appendChild(D),D.click(),document.body.removeChild(D)}else{const B=new hf,D=B.folder("images");w(0);for(let ue=0;ue{if(!r){alert("请先选择一个文件夹");return}b(!0),T(0);try{const A=i.filter(se=>se.folder&&se.folder.startsWith(r));if(A.length===0){alert("当前文件夹没有图片");return}const B=new hf,D=r.split("/").pop()||"images",le=B.folder(D);for(let se=0;seA<1024?A+" B":A<1024*1024?(A/1024).toFixed(2)+" KB":(A/(1024*1024)).toFixed(2)+" MB",F=A=>new Date(A).toLocaleString("zh-CN");return S.jsxs("div",{className:"w-full border-l border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 flex flex-col h-full",children:[l&&S.jsx("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700 flex items-center",children:S.jsxs("button",{onClick:()=>s("main"),className:"flex items-center gap-2 text-gray-700 dark:text-gray-300 hover:text-blue-500",children:[S.jsx(V1,{className:"w-5 h-5"}),S.jsx("span",{className:"text-sm font-medium",children:"返回"})]})}),S.jsx("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0",children:S.jsxs("div",{className:"w-full aspect-square bg-gray-100 dark:bg-gray-700 rounded-lg overflow-hidden relative",children:[S.jsx("img",{src:p,alt:O.filename,decoding:"async",className:`w-full h-full object-contain transition-opacity duration-300 ${x?"opacity-75":"opacity-100"}`}),x&&S.jsx("div",{className:"absolute top-2 right-2 bg-blue-500 text-white text-xs px-2 py-1 rounded",children:"加载原图中..."})]})}),S.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 min-h-0",children:S.jsxs("div",{children:[S.jsx("h3",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2",children:"基本信息"}),S.jsxs("div",{className:"space-y-2 text-sm",children:[S.jsxs("div",{children:[S.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"文件名:"}),S.jsx("p",{className:"text-gray-900 dark:text-gray-100 break-all",children:e.filename})]}),S.jsxs("div",{children:[S.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"尺寸:"}),S.jsxs("p",{className:"text-gray-900 dark:text-gray-100",children:[e.width," × ",e.height]})]}),S.jsxs("div",{children:[S.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"大小:"}),S.jsx("p",{className:"text-gray-900 dark:text-gray-100",children:z(e.size)})]}),S.jsxs("div",{children:[S.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"格式:"}),S.jsx("p",{className:"text-gray-900 dark:text-gray-100 uppercase",children:e.format})]}),S.jsxs("div",{children:[S.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"创建时间:"}),S.jsx("p",{className:"text-gray-900 dark:text-gray-100",children:F(e.created_at)})]}),S.jsxs("div",{children:[S.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"修改时间:"}),S.jsx("p",{className:"text-gray-900 dark:text-gray-100",children:F(e.modified_at)})]}),S.jsxs("div",{children:[S.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"路径:"}),S.jsx("p",{className:"text-gray-900 dark:text-gray-100 text-xs break-all",children:e.path})]})]})]})}),!l&&S.jsxs("div",{className:"p-4 border-t border-gray-200 dark:border-gray-700 space-y-2 flex-shrink-0",children:[S.jsx("button",{onClick:H,className:`w-full flex items-center justify-center gap-2 px-4 py-2 rounded-lg transition-all ${m?"bg-green-500 text-white":"bg-blue-500 text-white hover:bg-blue-600"}`,children:m?S.jsxs(S.Fragment,{children:[S.jsx(q1,{className:"w-4 h-4"}),S.jsxs("span",{children:["已复制",P?` ${t.length} 张`:""]})]}):S.jsxs(S.Fragment,{children:[S.jsx(Z1,{className:"w-4 h-4"}),S.jsxs("span",{children:["复制图片",P?` (${t.length})`:""]})]})}),S.jsxs("button",{onClick:U,disabled:v,className:"w-full flex flex-col items-center justify-center gap-2 px-4 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[S.jsxs("div",{className:"flex items-center gap-2",children:[S.jsx(Q1,{className:"w-4 h-4"}),S.jsx("span",{children:v?`打包中... ${h}%`:`导出图片${P?` (${t.length})`:""}`})]}),v&&P&&S.jsx("div",{className:"w-full bg-gray-300 dark:bg-gray-600 rounded-full h-1.5 mt-1",children:S.jsx("div",{className:"bg-blue-500 h-1.5 rounded-full transition-all duration-300",style:{width:`${h}%`}})})]}),r&&S.jsxs("button",{onClick:ee,disabled:k,className:"w-full flex flex-col items-center justify-center gap-2 px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[S.jsxs("div",{className:"flex items-center gap-2",children:[S.jsx(tw,{className:"w-4 h-4"}),S.jsx("span",{children:k?`打包文件夹... ${N}%`:"导出当前文件夹"})]}),k&&S.jsx("div",{className:"w-full bg-purple-300 rounded-full h-1.5 mt-1",children:S.jsx("div",{className:"bg-white h-1.5 rounded-full transition-all duration-300",style:{width:`${N}%`}})})]})]})]})}function mf(){const{theme:e,toggleTheme:t,searchKeywords:n,thumbnailHeight:r,images:i,filteredImages:s,selectedFolder:o,currentLibraryId:a,setSearchKeywords:l,setThumbnailHeight:d,setFilteredImages:p,mobileView:y}=me(),[x,g]=Z.useState(!1),[m,u]=Z.useState([]),[v,c]=Z.useState([]),[h,w]=Z.useState(""),[k,b]=Z.useState(!1),[N,T]=Z.useState(!1),[P,O]=Z.useState(!1),[M,J]=Z.useState(n),R=Z.useRef(null);Z.useEffect(()=>{const X=()=>{T(window.innerWidth<768)};return X(),window.addEventListener("resize",X),()=>window.removeEventListener("resize",X)},[]),Z.useEffect(()=>{u([]),c([]),w("")},[o]),Z.useEffect(()=>{if(a)return Vd.start(a).catch(X=>{console.error("启动文件监控失败:",X)}),()=>{Vd.stop(a).catch(X=>console.error("Stop watch error:",X))}},[a]);const W=X=>{J(X),R.current&&clearTimeout(R.current),R.current=setTimeout(()=>{l(X)},300)};Z.useEffect(()=>{J(n)},[n]),Z.useEffect(()=>()=>{R.current&&clearTimeout(R.current)},[]);const _=X=>{if(X.length===0)return[];const re=[...X].sort((j,Y)=>j-Y),q=re[0],ne=re[re.length-1];if(ne-q<10)return[V(q,ne)];const f=5,I=[],L=Math.log10(q||1),E=(Math.log10(ne)-L)/f;for(let j=0;jie>=Y&&iej)},V=(X,re,q=!1)=>{const ne=f=>{const I=L=>L<10?Math.round(L):L<100?Math.round(L/5)*5:L<1e3?Math.round(L/10)*10:Math.round(L/50)*50;return f<1?`${I(f*1024)}B`:f<1024?`${I(f)}KB`:f<1048576?`${I(f/1024)}MB`:`${I(f/1048576)}GB`};return q?`> ${ne(X)}`:`${ne(X)} - ${ne(re)}`},ce=X=>{const re=X.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB)$/);if(!re)return 0;const q=parseFloat(re[1]);switch(re[2]){case"B":return q/1024;case"KB":return q;case"MB":return q*1024;case"GB":return q*1024*1024;default:return 0}},Q=(X,re)=>{if(re.startsWith(">")){const q=re.substring(1).trim(),ne=ce(q);return X>=ne}else if(re.includes(" - ")){const[q,ne]=re.split(" - ").map(L=>L.trim()),f=ce(q),I=ce(ne);return X>=f&&X{if(i.length===0)return{formats:[],sizes:[],hasHorizontal:!1,hasVertical:!1};const X=new Set,re=[];let q=!1,ne=!1;i.forEach(I=>{I.format&&X.add(I.format.toLowerCase()),re.push(I.size/1024),I.width>I.height&&(q=!0),I.height>I.width&&(ne=!0)});const f=_(re);return{formats:Array.from(X).sort(),sizes:f,hasHorizontal:q,hasVertical:ne}},[i]),U=Z.useMemo(()=>{if(m.length===0&&v.length===0&&!h)return i;const X=new Set(m),re=new Set(v);return i.filter(q=>{var ne;if(X.size>0&&!X.has((ne=q.format)==null?void 0:ne.toLowerCase()))return!1;if(re.size>0){const f=q.size/1024;let I=!1;for(const L of re)if(Q(f,L)){I=!0;break}if(!I)return!1}if(h==="horizontal"){if(q.width<=q.height)return!1}else if(h==="vertical"&&q.height<=q.width)return!1;return!0})},[i,m,v,h]);Z.useEffect(()=>{p(U)},[U,p]);const ee=X=>{u(re=>re.includes(X)?re.filter(q=>q!==X):[...re,X])},z=X=>{c(re=>re.includes(X)?re.filter(q=>q!==X):[...re,X])},F=X=>{w(re=>re===X?"":X)},A=()=>{u([]),c([]),w("")},B=async()=>{t();try{await Nn.updateTheme(e==="light"?"dark":"light")}catch(X){console.error("Error saving theme:",X)}},D=async X=>{d(X);try{await Nn.updatePreferences({thumbnailHeight:X})}catch(re){console.error("Error saving preferences:",re)}},le=async()=>{if(!(!a||k)){b(!0);try{await sr.sync(a)}catch(X){console.error("Error refreshing:",X),alert("刷新失败: "+X.message)}finally{b(!1)}}},de=H.formats,ue=H.sizes.map(X=>({label:X})),se=[{value:"horizontal",label:"横图"},{value:"vertical",label:"竖图"}].filter(X=>X.value==="horizontal"&&H.hasHorizontal||X.value==="vertical"&&H.hasVertical);if(N){const X=y!=="sidebar";return S.jsxs("header",{className:"border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800",children:[S.jsxs("div",{className:"h-14 flex items-center justify-between px-4",children:[S.jsx("h1",{className:"text-lg font-bold text-gray-900 dark:text-white",children:"FlyPic"}),S.jsxs("div",{className:"flex items-center gap-2",children:[S.jsx("button",{onClick:le,disabled:!a||k,className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50",children:S.jsx(Yd,{className:`w-5 h-5 text-gray-700 dark:text-gray-300 ${k?"animate-spin":""}`})}),S.jsx("button",{onClick:()=>O(!P),className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors",children:S.jsx(Zd,{className:"w-5 h-5 text-gray-700 dark:text-gray-300"})}),S.jsx("button",{onClick:B,className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors",children:e==="light"?S.jsx(Xd,{className:"w-5 h-5 text-gray-700 dark:text-gray-300"}):S.jsx(Qd,{className:"w-5 h-5 text-gray-700 dark:text-gray-300"})})]})]}),X&&S.jsx("div",{className:"px-4 pb-3",children:S.jsxs("div",{className:"flex items-center gap-2",children:[S.jsxs("div",{className:"flex-1 relative",children:[S.jsx(Bo,{className:"absolute left-3 top-2.5 w-5 h-5 text-gray-400"}),S.jsx("input",{type:"text",placeholder:"搜索图片...",value:n,onChange:re=>W(re.target.value),className:"w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm"})]}),S.jsx("button",{onClick:()=>g(!x),className:`p-2 border rounded-lg ${m.length>0||v.length>0||h?"border-blue-500 bg-blue-50 dark:bg-blue-500/20":"border-gray-300 dark:border-gray-600"}`,children:S.jsx(Kd,{className:`w-5 h-5 ${m.length>0||v.length>0||h?"text-blue-600 dark:text-blue-300":"text-gray-600 dark:text-gray-400"}`})})]})}),P&&S.jsx("div",{className:"px-4 pb-3 border-t border-gray-200 dark:border-gray-700 pt-3",children:S.jsxs("div",{className:"flex flex-col gap-3",children:[S.jsxs("div",{className:"flex items-center justify-between",children:[S.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300",children:"缩略图大小"}),S.jsxs("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:[r,"px"]})]}),S.jsx("input",{type:"range",min:"150",max:"300",value:r,onChange:re=>D(parseInt(re.target.value)),className:"w-full h-2 bg-gray-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer",style:{background:`linear-gradient(to right, #3b82f6 0%, #3b82f6 ${(r-150)/150*100}%, #e5e7eb ${(r-150)/150*100}%, #e5e7eb 100%)`}})]})}),X&&x&&S.jsxs("div",{className:"px-4 pb-3 border-t border-gray-200 dark:border-gray-700 pt-3",children:[S.jsxs("div",{className:"flex items-center justify-between mb-3",children:[S.jsx("span",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"筛选条件"}),S.jsx("button",{onClick:A,className:"text-xs text-blue-500",children:"清除全部"})]}),S.jsxs("div",{className:"mb-3",children:[S.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-2",children:"格式"}),S.jsx("div",{className:"flex flex-wrap gap-2",children:de.map(re=>S.jsx("button",{onClick:()=>ee(re),className:`px-3 py-1 text-xs rounded-full ${m.includes(re)?"bg-blue-500 text-white":"bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300"}`,children:re.toUpperCase()},re))})]}),S.jsxs("div",{className:"mb-3",children:[S.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-2",children:"尺寸"}),S.jsx("div",{className:"flex flex-wrap gap-2",children:ue.map(re=>S.jsx("button",{onClick:()=>z(re.label),className:`px-3 py-1 text-xs rounded-full ${v.includes(re.label)?"bg-blue-500 text-white":"bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300"}`,children:re.label},re.label))})]}),S.jsxs("div",{children:[S.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-2",children:"方向"}),S.jsx("div",{className:"flex flex-wrap gap-2",children:se.map(re=>S.jsx("button",{onClick:()=>F(re.value),className:`px-3 py-1 text-xs rounded-full ${h===re.value?"bg-blue-500 text-white":"bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300"}`,children:re.label},re.value))})]})]})]})}return S.jsxs("header",{className:"border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800",children:[S.jsxs("div",{className:"h-14 flex items-center justify-between px-6",children:[S.jsxs("div",{className:"flex-shrink-0",children:[S.jsx("h1",{className:"text-xl font-bold text-gray-900 dark:text-white",children:"FlyPic"}),S.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"轻量快速的图片素材库管理"})]}),S.jsxs("div",{className:"flex-1 max-w-2xl mx-6 flex items-center gap-3",children:[S.jsxs("div",{className:"flex-1 relative",children:[S.jsx(Bo,{className:"absolute left-3 top-2.5 w-5 h-5 text-gray-400"}),S.jsx("input",{type:"text",placeholder:"搜索图片... (多个关键词用空格分隔,即时搜索)",value:M,onChange:X=>W(X.target.value),className:"w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),S.jsxs("button",{onClick:()=>g(!x),className:`relative p-2 border rounded-lg transition-colors ${m.length>0||v.length>0||h?"border-blue-500 dark:border-blue-400 bg-blue-50 dark:bg-blue-500/20 hover:bg-blue-100 dark:hover:bg-blue-500/30":"border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700"}`,title:m.length>0||v.length>0||h?"筛选(已启用)":"筛选",children:[S.jsx(Kd,{className:`w-5 h-5 ${m.length>0||v.length>0||h?"text-blue-600 dark:text-blue-300":"text-gray-600 dark:text-gray-400"}`}),(m.length>0||v.length>0||h)&&S.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full",style:{backgroundColor:"#3b82f6"}})]})]}),S.jsxs("div",{className:"flex items-center gap-3 flex-shrink-0",children:[S.jsx(Zd,{className:"w-4 h-4 text-gray-500"}),S.jsx("input",{type:"range",min:"150",max:"300",value:r,onChange:X=>D(parseInt(X.target.value)),className:"w-32"}),S.jsxs("span",{className:"text-sm text-gray-600 dark:text-gray-400 w-12",children:[r,"px"]}),S.jsx("button",{onClick:le,disabled:!a||k,className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed ml-2",title:"手动刷新素材库(文件监控已自动启用)",children:S.jsx(Yd,{className:`w-5 h-5 text-gray-700 dark:text-gray-300 ${k?"animate-spin":""}`})}),S.jsx("button",{onClick:B,className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors",title:e==="light"?"切换到暗色模式":"切换到亮色模式",children:e==="light"?S.jsx(Xd,{className:"w-5 h-5 text-gray-700 dark:text-gray-300"}):S.jsx(Qd,{className:"w-5 h-5 text-gray-700 dark:text-gray-300"})})]})]}),x&&S.jsx("div",{className:"px-6 pb-3",children:S.jsxs("div",{className:"p-4 bg-gray-50 dark:bg-gray-700 rounded-lg",children:[S.jsxs("div",{className:"flex items-center justify-between mb-3",children:[S.jsx("div",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"筛选条件(实时生效)"}),S.jsx("button",{onClick:A,className:"text-xs text-blue-500 hover:text-blue-600 dark:hover:text-blue-400",children:"清除全部"})]}),S.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[S.jsxs("div",{children:[S.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-2",children:"格式"}),S.jsx("div",{className:"flex flex-col gap-1.5",children:H.formats.length>0?H.formats.map(X=>S.jsx("button",{onClick:()=>ee(X),className:`px-3 py-1.5 text-xs rounded transition-colors text-left ${m.includes(X)?"bg-blue-500 text-white":"bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500"}`,children:X.toUpperCase()},X)):S.jsx("span",{className:"text-xs text-gray-400 py-2",children:"暂无格式数据"})})]}),S.jsxs("div",{children:[S.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-2",children:"文件大小"}),S.jsx("div",{className:"flex flex-col gap-1.5",children:H.sizes.length>0?H.sizes.map(X=>S.jsx("button",{onClick:()=>z(X),className:`px-3 py-1.5 text-xs rounded transition-colors text-left ${v.includes(X)?"bg-blue-500 text-white":"bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500"}`,children:X},X)):S.jsx("span",{className:"text-xs text-gray-400 py-2",children:"暂无大小数据"})})]}),S.jsxs("div",{children:[S.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-2",children:"图片方向"}),S.jsxs("div",{className:"flex flex-col gap-1.5",children:[H.hasHorizontal&&S.jsx("button",{onClick:()=>F("horizontal"),className:`px-3 py-1.5 text-xs rounded transition-colors text-left ${h==="horizontal"?"bg-blue-500 text-white":"bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500"}`,children:"横图"}),H.hasVertical&&S.jsx("button",{onClick:()=>F("vertical"),className:`px-3 py-1.5 text-xs rounded transition-colors text-left ${h==="vertical"?"bg-blue-500 text-white":"bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500"}`,children:"竖图"}),!H.hasHorizontal&&!H.hasVertical&&S.jsx("span",{className:"text-xs text-gray-400 py-2",children:"暂无方向数据"})]})]})]})]})})]})}function Yw(){const{theme:e,setLibraries:t,setCurrentLibrary:n,setScanProgress:r,mobileView:i,setMobileView:s,selectedImage:o}=me(),[a,l]=Z.useState(256),[d,p]=Z.useState(320),[y,x]=Z.useState(!1),[g,m]=Z.useState(!1),[u,v]=Z.useState(!1),c=Z.useRef(null);Z.useEffect(()=>{e==="dark"?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark")},[e]),Z.useEffect(()=>{const k=()=>{const b=window.innerWidth<768;v(b)};return k(),window.addEventListener("resize",k),()=>window.removeEventListener("resize",k)},[]),Z.useEffect(()=>{u&&o&&s("detail")},[o,u,s]),Z.useEffect(()=>{const k=window.location.origin;console.log("🔌 Connecting to Socket.IO:",k);const b=co(k,{transports:["websocket","polling"],reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:5});return b.on("connect",()=>{console.log("✅ Socket.IO connected:",b.id)}),b.on("disconnect",()=>{console.log("❌ Socket.IO disconnected")}),b.on("connect_error",N=>{console.error("❌ Socket.IO connection error:",N)}),b.on("scanProgress",N=>{const T=me.getState().currentLibraryId;N.libraryId===T&&r(N)}),b.on("scanComplete",({libraryId:N,results:T})=>{console.log("📊 Scan complete:",{libraryId:N,results:T});const P=me.getState().currentLibraryId;if(console.log("🔍 Current library:",P,"Scan library:",N,"Match:",N===P),N===P){console.log("🔄 Reloading folders and images...");const O=me.getState(),M={keywords:O.searchKeywords,...O.filters};O.selectedFolder&&(M.folder=O.selectedFolder),Promise.all([Me.getFolders(N),O.selectedFolder||O.searchKeywords||O.filters.formats.length>0?Me.search(N,M):Promise.resolve({data:{images:[]}}),Me.getCount(N)]).then(([J,R,W])=>{me.getState().setFolders(J.data.folders),me.getState().setImages(R.data.images),me.getState().setTotalImageCount(W.data.count),console.log(`✅ Data reloaded, total: ${W.data.count}`)}).catch(J=>{console.error("❌ Error reloading data:",J)}).finally(()=>{r(null),console.log("✅ Scan progress cleared")})}else console.log("⚠️ Library mismatch, skipping reload"),r(null)}),b.on("scanError",({libraryId:N,error:T})=>{r(null),console.error("Scan error:",T)}),b.on("scanPaused",({libraryId:N,results:T})=>{console.log("⏸️ Scan paused:",{libraryId:N,results:T})}),h(),()=>{b.disconnect()}},[]);const h=async()=>{try{const k=await Nn.getAll(),{libraries:b,currentLibraryId:N,theme:T,preferences:P}=k.data;if(t(b),n(N),T&&me.getState().setTheme(T),P){const{thumbnailHeight:O,leftPanelWidth:M,rightPanelWidth:J}=P;O&&me.getState().setThumbnailHeight(O),M&&l(M),J&&p(J)}if(N){const[O]=await Promise.all([Me.getFolders(N)]);me.getState().setFolders(O.data.folders);try{const M=await Me.getCount(N);me.getState().setTotalImageCount(M.data.count)}catch(M){console.error("Failed to get image count:",M)}console.log("📂 数据加载完成,文件监控器将自动检测变化"),sr.getStatus(N).then(M=>{const{status:J,progress:R,pendingCount:W}=M.data;(J==="scanning"||J==="paused")&&(console.log(`🔄 恢复扫描状态: ${J}, 进度: ${(R==null?void 0:R.percent)||0}%`),r({...R,canStop:!0,isPaused:J==="paused",pendingCount:W}))}).catch(()=>{})}}catch(k){console.error("Error loading libraries:",k)}},w=async(k,b)=>{try{await Nn.updatePreferences({leftPanelWidth:k,rightPanelWidth:b})}catch(N){console.error("Error saving panel widths:",N)}};return Z.useEffect(()=>{if(!y&&!g)return;const k=document.getElementById("left-panel"),b=document.getElementById("right-panel");let N=a,T=d;const P=c.current.getBoundingClientRect(),O=P.left,M=P.right;let J=null,R=null,W=null;const _=()=>{k&&R!=null&&(k.style.width=`${R}px`,N=R),b&&W!=null&&(b.style.width=`${W}px`,T=W),J=null,R=null,W=null},V=Q=>{let H=!1;if(y&&k){const U=Q.clientX-O;U>=200&&U<=400&&(R=U,H=!0)}if(g&&b){const U=M-Q.clientX;U>=280&&U<=500&&(W=U,H=!0)}H&&J==null&&(J=requestAnimationFrame(_))},ce=()=>{J&&(cancelAnimationFrame(J),_()),l(N),p(T),w(N,T),x(!1),m(!1),me.getState().setIsResizingPanels(!1),me.getState().setResizingSide(null)};return document.addEventListener("mousemove",V,{passive:!0}),document.addEventListener("mouseup",ce),document.body.style.userSelect="none",document.body.style.cursor="col-resize",k&&(k.style.transition="none"),b&&(b.style.transition="none"),()=>{J&&(cancelAnimationFrame(J),J=null),document.removeEventListener("mousemove",V),document.removeEventListener("mouseup",ce),document.body.style.userSelect="",document.body.style.cursor="",k&&(k.style.transition=""),b&&(b.style.transition="")}},[y,g]),u?S.jsxs("div",{className:"flex flex-col h-screen bg-gray-50 dark:bg-gray-900",children:[S.jsx(mf,{}),S.jsxs("div",{className:"flex-1 overflow-hidden relative",children:[S.jsx("div",{className:`absolute inset-0 transition-transform duration-300 ${i==="sidebar"?"translate-x-0":"-translate-x-full"}`,children:S.jsx(Jd,{})}),S.jsx("div",{className:`absolute inset-0 transition-transform duration-300 ${i==="main"?"translate-x-0":i==="sidebar"?"translate-x-full":"-translate-x-full"}`,children:S.jsx(ff,{})}),S.jsx("div",{className:`absolute inset-0 transition-transform duration-300 ${i==="detail"?"translate-x-0":"translate-x-full"}`,children:S.jsx(pf,{})})]}),S.jsxs("div",{className:"flex border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800",children:[S.jsxs("button",{onClick:()=>s("sidebar"),className:`flex-1 flex flex-col items-center py-2 ${i==="sidebar"?"text-blue-500":"text-gray-500"}`,children:[S.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:S.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"})}),S.jsx("span",{className:"text-xs mt-1",children:"文件夹"})]}),S.jsxs("button",{onClick:()=>s("main"),className:`flex-1 flex flex-col items-center py-2 ${i==="main"?"text-blue-500":"text-gray-500"}`,children:[S.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:S.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})}),S.jsx("span",{className:"text-xs mt-1",children:"图片"})]}),S.jsxs("button",{onClick:()=>s("detail"),disabled:!o,className:`flex-1 flex flex-col items-center py-2 ${i==="detail"?"text-blue-500":"text-gray-500"} disabled:opacity-30`,children:[S.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:S.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),S.jsx("span",{className:"text-xs mt-1",children:"详情"})]})]})]}):S.jsxs("div",{className:"flex flex-col h-screen bg-gray-50 dark:bg-gray-900",children:[S.jsx(mf,{}),S.jsxs("div",{ref:c,className:"flex flex-1 overflow-hidden",children:[S.jsx("div",{id:"left-panel",style:{width:`${a}px`},className:"flex-shrink-0 h-full",children:S.jsx(Jd,{})}),S.jsx("div",{className:`group relative w-1 h-full cursor-col-resize flex-shrink-0 transition-colors ${y?"bg-blue-500":"bg-gray-200 dark:bg-gray-700 hover:bg-blue-400"}`,onMouseDown:k=>{k.preventDefault(),me.getState().setIsResizingPanels(!0),me.getState().setResizingSide("left"),x(!0)},children:S.jsx("div",{className:"absolute inset-y-0 -left-2 -right-2 w-5"})}),S.jsx("div",{className:"flex-1 min-w-0 h-full",children:S.jsx(ff,{})}),S.jsx("div",{className:`group relative w-1 h-full cursor-col-resize flex-shrink-0 transition-colors ${g?"bg-blue-500":"bg-gray-200 dark:bg-gray-700 hover:bg-blue-400"}`,onMouseDown:k=>{k.preventDefault(),me.getState().setIsResizingPanels(!0),me.getState().setResizingSide("right"),m(!0)},children:S.jsx("div",{className:"absolute inset-y-0 -left-2 -right-2 w-5"})}),S.jsx("div",{id:"right-panel",style:{width:`${d}px`},className:"flex-shrink-0 h-full",children:S.jsx(pf,{})})]})]})}Za.createRoot(document.getElementById("root")).render(S.jsx(ke.StrictMode,{children:S.jsx(Yw,{})})); diff --git a/flypic/app/server/public/assets/index-CcwAM3eE.css b/flypic/app/server/public/assets/index-CcwAM3eE.css new file mode 100644 index 0000000..f44d34c --- /dev/null +++ b/flypic/app/server/public/assets/index-CcwAM3eE.css @@ -0,0 +1 @@ +.PhotoView-Portal{direction:ltr;height:100%;left:0;overflow:hidden;position:fixed;top:0;touch-action:none;width:100%;z-index:2000}@keyframes PhotoView__rotate{0%{transform:rotate(0)}to{transform:rotate(1turn)}}@keyframes PhotoView__delayIn{0%,50%{opacity:0}to{opacity:1}}.PhotoView__Spinner{animation:PhotoView__delayIn .4s linear both}.PhotoView__Spinner svg{animation:PhotoView__rotate .6s linear infinite}.PhotoView__Photo{cursor:grab;max-width:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.PhotoView__Photo:active{cursor:grabbing}.PhotoView__icon{display:inline-block;left:0;position:absolute;top:0;transform:translate(-50%,-50%)}.PhotoView__PhotoBox,.PhotoView__PhotoWrap{bottom:0;direction:ltr;left:0;position:absolute;right:0;top:0;touch-action:none;width:100%}.PhotoView__PhotoWrap{overflow:hidden;z-index:10}.PhotoView__PhotoBox{transform-origin:left top}@keyframes PhotoView__fade{0%{opacity:0}to{opacity:1}}.PhotoView-Slider__clean .PhotoView-Slider__ArrowLeft,.PhotoView-Slider__clean .PhotoView-Slider__ArrowRight,.PhotoView-Slider__clean .PhotoView-Slider__BannerWrap,.PhotoView-Slider__clean .PhotoView-Slider__Overlay,.PhotoView-Slider__willClose .PhotoView-Slider__BannerWrap:hover{opacity:0}.PhotoView-Slider__Backdrop{background:#000;height:100%;left:0;position:absolute;top:0;transition-property:background-color;width:100%;z-index:-1}.PhotoView-Slider__fadeIn{animation:PhotoView__fade linear both;opacity:0}.PhotoView-Slider__fadeOut{animation:PhotoView__fade linear reverse both;opacity:0}.PhotoView-Slider__BannerWrap{align-items:center;background-color:#00000080;color:#fff;display:flex;height:44px;justify-content:space-between;left:0;position:absolute;top:0;transition:opacity .2s ease-out;width:100%;z-index:20}.PhotoView-Slider__BannerWrap:hover{opacity:1}.PhotoView-Slider__Counter{font-size:14px;opacity:.75;padding:0 10px}.PhotoView-Slider__BannerRight{align-items:center;display:flex;height:100%}.PhotoView-Slider__toolbarIcon{fill:#fff;box-sizing:border-box;cursor:pointer;opacity:.75;padding:10px;transition:opacity .2s linear}.PhotoView-Slider__toolbarIcon:hover{opacity:1}.PhotoView-Slider__ArrowLeft,.PhotoView-Slider__ArrowRight{align-items:center;bottom:0;cursor:pointer;display:flex;height:100px;justify-content:center;margin:auto;opacity:.75;position:absolute;top:0;transition:opacity .2s linear;-webkit-user-select:none;-moz-user-select:none;user-select:none;width:70px;z-index:20}.PhotoView-Slider__ArrowLeft:hover,.PhotoView-Slider__ArrowRight:hover{opacity:1}.PhotoView-Slider__ArrowLeft svg,.PhotoView-Slider__ArrowRight svg{fill:#fff;background:#0000004d;box-sizing:content-box;height:24px;padding:10px;width:24px}.PhotoView-Slider__ArrowLeft{left:0}.PhotoView-Slider__ArrowRight{right:0}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.\!container{width:100%!important}.container{width:100%}@media (min-width: 640px){.\!container{max-width:640px!important}.container{max-width:640px}}@media (min-width: 768px){.\!container{max-width:768px!important}.container{max-width:768px}}@media (min-width: 1024px){.\!container{max-width:1024px!important}.container{max-width:1024px}}@media (min-width: 1280px){.\!container{max-width:1280px!important}.container{max-width:1280px}}@media (min-width: 1536px){.\!container{max-width:1536px!important}.container{max-width:1536px}}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.inset-y-0{top:0;bottom:0}.-bottom-0\.5{bottom:-.125rem}.-left-2{left:-.5rem}.-right-0\.5{right:-.125rem}.-right-2{right:-.5rem}.left-0{left:0}.left-2{left:.5rem}.left-3{left:.75rem}.right-0{right:0}.right-2{right:.5rem}.top-0{top:0}.top-2{top:.5rem}.top-2\.5{top:.625rem}.-z-10{z-index:-10}.z-10{z-index:10}.z-50{z-index:50}.mx-6{margin-left:1.5rem;margin-right:1.5rem}.mx-auto{margin-left:auto;margin-right:auto}.my-2{margin-top:.5rem;margin-bottom:.5rem}.mb-12{margin-bottom:3rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-8{margin-bottom:2rem}.ml-2{margin-left:.5rem}.mr-1{margin-right:.25rem}.mr-2{margin-right:.5rem}.mt-1{margin-top:.25rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.block{display:block}.flex{display:flex}.grid{display:grid}.aspect-square{aspect-ratio:1 / 1}.h-1\.5{height:.375rem}.h-12{height:3rem}.h-14{height:3.5rem}.h-16{height:4rem}.h-2{height:.5rem}.h-3{height:.75rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-8{height:2rem}.h-full{height:100%}.h-px{height:1px}.h-screen{height:100vh}.max-h-full{max-height:100%}.min-h-0{min-height:0px}.w-1{width:.25rem}.w-12{width:3rem}.w-3{width:.75rem}.w-32{width:8rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-64{width:16rem}.w-8{width:2rem}.w-80{width:20rem}.w-96{width:24rem}.w-full{width:100%}.min-w-0{min-width:0px}.max-w-2xl{max-width:42rem}.max-w-4xl{max-width:56rem}.max-w-full{max-width:100%}.max-w-md{max-width:28rem}.max-w-sm{max-width:24rem}.flex-1{flex:1 1 0%}.flex-shrink-0{flex-shrink:0}.-translate-x-full{--tw-translate-x: -100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-0{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-full{--tw-translate-x: 100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-col-resize{cursor:col-resize}.cursor-pointer{cursor:pointer}.resize{resize:both}.appearance-none{-webkit-appearance:none;-moz-appearance:none;appearance:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-8>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(2rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(2rem * var(--tw-space-y-reverse))}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-blue-200{--tw-border-opacity: 1;border-color:rgb(191 219 254 / var(--tw-border-opacity, 1))}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-gray-100{--tw-border-opacity: 1;border-color:rgb(243 244 246 / var(--tw-border-opacity, 1))}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-red-300{--tw-border-opacity: 1;border-color:rgb(252 165 165 / var(--tw-border-opacity, 1))}.bg-black{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-blue-200{--tw-bg-opacity: 1;background-color:rgb(191 219 254 / var(--tw-bg-opacity, 1))}.bg-blue-50{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.bg-gray-300{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-gray-500{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity, 1))}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-indigo-100{--tw-bg-opacity: 1;background-color:rgb(224 231 255 / var(--tw-bg-opacity, 1))}.bg-pink-500{--tw-bg-opacity: 1;background-color:rgb(236 72 153 / var(--tw-bg-opacity, 1))}.bg-purple-100{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.bg-purple-300{--tw-bg-opacity: 1;background-color:rgb(216 180 254 / var(--tw-bg-opacity, 1))}.bg-purple-500{--tw-bg-opacity: 1;background-color:rgb(168 85 247 / var(--tw-bg-opacity, 1))}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-opacity-0{--tw-bg-opacity: 0}.bg-opacity-50{--tw-bg-opacity: .5}.bg-opacity-90{--tw-bg-opacity: .9}.fill-white{fill:#fff}.object-contain{-o-object-fit:contain;object-fit:contain}.object-cover{-o-object-fit:cover;object-fit:cover}.p-1{padding:.25rem}.p-2{padding:.5rem}.p-20{padding:5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pb-3{padding-bottom:.75rem}.pl-10{padding-left:2.5rem}.pl-8{padding-left:2rem}.pr-3{padding-right:.75rem}.pr-4{padding-right:1rem}.pt-3{padding-top:.75rem}.text-left{text-align:left}.text-center{text-align:center}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-6xl{font-size:3.75rem;line-height:1}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-blue-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-indigo-600{--tw-text-opacity: 1;color:rgb(79 70 229 / var(--tw-text-opacity, 1))}.text-purple-600{--tw-text-opacity: 1;color:rgb(147 51 234 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-500{--tw-text-opacity: 1;color:rgb(234 179 8 / var(--tw-text-opacity, 1))}.opacity-100{opacity:1}.opacity-70{opacity:.7}.opacity-75{opacity:.75}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-shadow{transition-property:box-shadow;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-300{transition-duration:.3s}*{margin:0;padding:0;box-sizing:border-box}body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}#root{width:100vw;height:100vh;overflow:hidden}.dark{--tw-bg-opacity: 1}.dark .bg-gray-900{background-color:#0a0a0a!important}.dark .bg-gray-800{background-color:#252525!important}.dark .bg-gray-700{background-color:#2a2a2a!important}.dark .bg-gray-600,.dark .bg-gray-500{background-color:#3a3a3a!important}.dark .bg-gray-400{background-color:#4a4a4a!important}.dark .bg-gray-300{background-color:#2a2a2a!important}.dark .bg-gray-200:not(img):not(.image-container){background-color:#2a2a2a!important}.dark .bg-gray-100,.dark .bg-gray-50,.dark .bg-white{background-color:#1a1a1a!important}.dark .border-gray-700{border-color:#333!important}.dark .border-gray-600{border-color:#444!important}.dark .border-gray-300{border-color:#333!important}.dark .border-gray-200,.dark .border-gray-100{border-color:#2a2a2a!important}.dark .text-gray-900{color:#f5f5f5!important}.dark .text-gray-700{color:#e0e0e0!important}.dark .text-gray-600{color:#b0b0b0!important}.dark .text-gray-500{color:#909090!important}.dark .text-gray-400{color:#707070!important}.dark .text-gray-300{color:#d0d0d0!important}.dark .text-white{color:#fff!important}.dark .text-gray-800{color:#e0e0e0!important}.dark .text-gray-200{color:#d0d0d0!important}.dark .text-gray-100{color:#e0e0e0!important}.dark .bg-opacity-0{--tw-bg-opacity: 0 !important}.dark .bg-opacity-10{--tw-bg-opacity: .1 !important}.dark .bg-opacity-20{--tw-bg-opacity: .2 !important}.dark .bg-opacity-30{--tw-bg-opacity: .3 !important}.dark .bg-opacity-50{--tw-bg-opacity: .5 !important}.dark .hover\:bg-gray-100:hover{background-color:#2a2a2a!important}.dark .hover\:bg-gray-700:hover{background-color:#333!important}.dark .hover\:bg-gray-600:hover{background-color:#3a3a3a!important}.dark .hover\:bg-gray-200:hover,.dark .hover\:bg-gray-50:hover{background-color:#2a2a2a!important}.dark .bg-black:not(.bg-opacity-0):not(.bg-opacity-10):not(.bg-opacity-20):not(.bg-opacity-30){background-color:#0a0a0a!important}.dark .text-black{color:#fff!important}.dark .border-black{border-color:#2a2a2a!important}.dark .bg-blue-50,.dark .bg-blue-100{background-color:#2a2a2a!important}.dark .bg-blue-200{background-color:#3a3a3a!important}.dark .bg-blue-600{background-color:#3a3a3a!important}.dark .bg-blue-800{background-color:#2a2a2a!important}.dark .bg-blue-900{background-color:#1a1a1a!important}.dark .text-blue-300{color:#d0d0d0!important}.dark .text-blue-400{color:#e0e0e0!important}.dark .text-blue-500,.dark .text-blue-600{color:#f0f0f0!important}.dark .text-blue-700{color:#e0e0e0!important}.dark .border-blue-200{border-color:#2a2a2a!important}.dark .border-blue-500{border-color:#4a4a4a!important}.dark .border-blue-700{border-color:#333!important}.dark .hover\:bg-blue-600:hover{background-color:#4a4a4a!important}.dark .hover\:bg-blue-50:hover{background-color:#333!important}.dark .bg-green-50{background-color:#2a2a2a!important}.dark .text-green-600{color:#e0e0e0!important}.dark .bg-red-50{background-color:#2a2a2a!important}.dark .text-red-600{color:#f0a0a0!important}.dark .bg-yellow-50{background-color:#2a2a2a!important}.dark .text-yellow-600{color:#e0e0a0!important}.dark img{background-color:transparent!important}.dark input,.dark select,.dark textarea{background-color:#1a1a1a!important;border-color:#333!important;color:#e0e0e0!important}.dark input:focus,.dark select:focus,.dark textarea:focus{border-color:#4a4a4a!important;outline:none!important;--tw-ring-color: #4a4a4a !important}.dark input::-moz-placeholder{color:#707070!important}.dark input::placeholder{color:#707070!important}.dark button{color:#e0e0e0!important}.dark .bg-blue-500{background-color:#4a4a4a!important}.dark .hover\:bg-blue-600:hover{background-color:#5a5a5a!important}.dark .shadow-lg{box-shadow:0 10px 15px -3px #00000080,0 4px 6px -2px #0000004d!important}.dark .shadow-xl{box-shadow:0 20px 25px -5px #00000080,0 10px 10px -5px #0000004d!important}.dark .hover\:shadow-lg:hover{box-shadow:0 10px 15px -3px #00000080,0 4px 6px -2px #0000004d!important}.dark .ring-blue-500{--tw-ring-color: #4a4a4a !important}.dark .focus\:ring-blue-500:focus{--tw-ring-color: #4a4a4a !important}.dark .focus\:ring-2:focus{--tw-ring-offset-shadow: 0 0 0 0px #000 !important;--tw-ring-shadow: 0 0 0 2px #4a4a4a !important}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:#0003;border-radius:4px}::-webkit-scrollbar-thumb:hover{background:#0000004d}.dark ::-webkit-scrollbar-track{background:#ffffff0d}.dark ::-webkit-scrollbar-thumb{background:#fff3;border-radius:4px}.dark ::-webkit-scrollbar-thumb:hover{background:#ffffff4d}.hover\:bg-blue-100:hover{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-400:hover{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-600:hover{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-300:hover{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.hover\:bg-purple-600:hover{--tw-bg-opacity: 1;background-color:rgb(147 51 234 / var(--tw-bg-opacity, 1))}.hover\:bg-red-50:hover{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.hover\:bg-white:hover{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.hover\:bg-opacity-20:hover{--tw-bg-opacity: .2}.hover\:text-blue-500:hover{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.hover\:text-blue-600:hover{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.hover\:shadow-lg:hover{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-md:hover{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-blue-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-30:disabled{opacity:.3}.disabled\:opacity-50:disabled{opacity:.5}.group:hover .group-hover\:bg-opacity-20{--tw-bg-opacity: .2}.group:hover .group-hover\:text-yellow-400{--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.dark\:border-blue-400:is(.dark *){--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.dark\:border-blue-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(29 78 216 / var(--tw-border-opacity, 1))}.dark\:border-gray-600:is(.dark *){--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.dark\:border-gray-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.dark\:border-red-600:is(.dark *){--tw-border-opacity: 1;border-color:rgb(220 38 38 / var(--tw-border-opacity, 1))}.dark\:bg-blue-500\/20:is(.dark *){background-color:#3b82f633}.dark\:bg-blue-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(30 64 175 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(30 58 138 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-900\/30:is(.dark *){background-color:#1e3a8a4d}.dark\:bg-gray-600:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-700:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.dark\:bg-indigo-900\/30:is(.dark *){background-color:#312e814d}.dark\:bg-purple-900\/30:is(.dark *){background-color:#581c874d}.dark\:text-blue-300:is(.dark *){--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.dark\:text-blue-400:is(.dark *){--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.dark\:text-gray-100:is(.dark *){--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity, 1))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.dark\:text-gray-500:is(.dark *){--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.dark\:text-gray-600:is(.dark *){--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.dark\:text-indigo-400:is(.dark *){--tw-text-opacity: 1;color:rgb(129 140 248 / var(--tw-text-opacity, 1))}.dark\:text-purple-400:is(.dark *){--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.dark\:text-red-400:is(.dark *){--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.dark\:text-white:is(.dark *){--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.dark\:hover\:bg-blue-500\/30:hover:is(.dark *){background-color:#3b82f64d}.dark\:hover\:bg-gray-500:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity, 1))}.dark\:hover\:bg-gray-600:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.dark\:hover\:bg-gray-700:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.dark\:hover\:bg-red-900:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(127 29 29 / var(--tw-bg-opacity, 1))}.dark\:hover\:text-blue-400:hover:is(.dark *){--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}@media (min-width: 768px){.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}@media (min-width: 1024px){.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}} diff --git a/flypic/app/server/public/assets/index-DWWYNoqs.js b/flypic/app/server/public/assets/index-DWWYNoqs.js new file mode 100644 index 0000000..16b3809 --- /dev/null +++ b/flypic/app/server/public/assets/index-DWWYNoqs.js @@ -0,0 +1,226 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function r(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function n(i){if(i.ep)return;i.ep=!0;const s=r(i);fetch(i.href,s)}})();var us=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Il(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var _d={exports:{}},_o={},kd={exports:{}},we={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var ns=Symbol.for("react.element"),sp=Symbol.for("react.portal"),op=Symbol.for("react.fragment"),ap=Symbol.for("react.strict_mode"),lp=Symbol.for("react.profiler"),up=Symbol.for("react.provider"),cp=Symbol.for("react.context"),dp=Symbol.for("react.forward_ref"),fp=Symbol.for("react.suspense"),hp=Symbol.for("react.memo"),pp=Symbol.for("react.lazy"),Ou=Symbol.iterator;function mp(e){return e===null||typeof e!="object"?null:(e=Ou&&e[Ou]||e["@@iterator"],typeof e=="function"?e:null)}var Sd={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},bd=Object.assign,Cd={};function ui(e,t,r){this.props=e,this.context=t,this.refs=Cd,this.updater=r||Sd}ui.prototype.isReactComponent={};ui.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};ui.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Ed(){}Ed.prototype=ui.prototype;function jl(e,t,r){this.props=e,this.context=t,this.refs=Cd,this.updater=r||Sd}var Ll=jl.prototype=new Ed;Ll.constructor=jl;bd(Ll,ui.prototype);Ll.isPureReactComponent=!0;var Au=Array.isArray,Nd=Object.prototype.hasOwnProperty,Ol={current:null},Rd={key:!0,ref:!0,__self:!0,__source:!0};function Td(e,t,r){var n,i={},s=null,o=null;if(t!=null)for(n in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(s=""+t.key),t)Nd.call(t,n)&&!Rd.hasOwnProperty(n)&&(i[n]=t[n]);var a=arguments.length-2;if(a===1)i.children=r;else if(1>>1,A=Y[M];if(0>>1;Mi(N,J))Vi(j,N)?(Y[M]=j,Y[V]=J,M=V):(Y[M]=N,Y[B]=J,M=B);else if(Vi(j,J))Y[M]=j,Y[V]=J,M=V;else break e}}return $}function i(Y,$){var J=Y.sortIndex-$.sortIndex;return J!==0?J:Y.id-$.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;e.unstable_now=function(){return s.now()}}else{var o=Date,a=o.now();e.unstable_now=function(){return o.now()-a}}var l=[],h=[],w=1,y=null,v=3,p=!1,x=!1,u=!1,_=typeof setTimeout=="function"?setTimeout:null,c=typeof clearTimeout=="function"?clearTimeout:null,d=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function g(Y){for(var $=r(h);$!==null;){if($.callback===null)n(h);else if($.startTime<=Y)n(h),$.sortIndex=$.expirationTime,t(l,$);else break;$=r(h)}}function S(Y){if(u=!1,g(Y),!x)if(r(l)!==null)x=!0,oe(b);else{var $=r(h);$!==null&&Q(S,$.startTime-Y)}}function b(Y,$){x=!1,u&&(u=!1,c(O),O=-1),p=!0;var J=v;try{for(g($),y=r(l);y!==null&&(!(y.expirationTime>$)||Y&&!re());){var M=y.callback;if(typeof M=="function"){y.callback=null,v=y.priorityLevel;var A=M(y.expirationTime<=$);$=e.unstable_now(),typeof A=="function"?y.callback=A:y===r(l)&&n(l),g($)}else n(l);y=r(l)}if(y!==null)var le=!0;else{var B=r(h);B!==null&&Q(S,B.startTime-$),le=!1}return le}finally{y=null,v=J,p=!1}}var R=!1,z=null,O=-1,I=5,P=-1;function re(){return!(e.unstable_now()-PY||125M?(Y.sortIndex=J,t(h,Y),r(l)===null&&Y===r(h)&&(u?(c(O),O=-1):u=!0,Q(S,J-M))):(Y.sortIndex=A,t(l,Y),x||p||(x=!0,oe(b))),Y},e.unstable_shouldYield=re,e.unstable_wrapCallback=function(Y){var $=v;return function(){var J=v;v=$;try{return Y.apply(this,arguments)}finally{v=J}}}})(Od);Ld.exports=Od;var Ep=Ld.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Np=G,_t=Ep;function se(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Ca=Object.prototype.hasOwnProperty,Rp=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Mu={},Du={};function Tp(e){return Ca.call(Du,e)?!0:Ca.call(Mu,e)?!1:Rp.test(e)?Du[e]=!0:(Mu[e]=!0,!1)}function zp(e,t,r,n){if(r!==null&&r.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return n?!1:r!==null?!r.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Ip(e,t,r,n){if(t===null||typeof t>"u"||zp(e,t,r,n))return!0;if(n)return!1;if(r!==null)switch(r.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function ut(e,t,r,n,i,s,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=n,this.attributeNamespace=i,this.mustUseProperty=r,this.propertyName=e,this.type=t,this.sanitizeURL=s,this.removeEmptyString=o}var Xe={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Xe[e]=new ut(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Xe[t]=new ut(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Xe[e]=new ut(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Xe[e]=new ut(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Xe[e]=new ut(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Xe[e]=new ut(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Xe[e]=new ut(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Xe[e]=new ut(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Xe[e]=new ut(e,5,!1,e.toLowerCase(),null,!1,!1)});var Pl=/[\-:]([a-z])/g;function Ml(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Pl,Ml);Xe[t]=new ut(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Pl,Ml);Xe[t]=new ut(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Pl,Ml);Xe[t]=new ut(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Xe[e]=new ut(e,1,!1,e.toLowerCase(),null,!1,!1)});Xe.xlinkHref=new ut("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Xe[e]=new ut(e,1,!1,e.toLowerCase(),null,!0,!0)});function Dl(e,t,r,n){var i=Xe.hasOwnProperty(t)?Xe[t]:null;(i!==null?i.type!==0:n||!(2a||i[o]!==s[a]){var l=` +`+i[o].replace(" at new "," at ");return e.displayName&&l.includes("")&&(l=l.replace("",e.displayName)),l}while(1<=o&&0<=a);break}}}finally{Ho=!1,Error.prepareStackTrace=r}return(e=e?e.displayName||e.name:"")?bi(e):""}function jp(e){switch(e.tag){case 5:return bi(e.type);case 16:return bi("Lazy");case 13:return bi("Suspense");case 19:return bi("SuspenseList");case 0:case 2:case 15:return e=qo(e.type,!1),e;case 11:return e=qo(e.type.render,!1),e;case 1:return e=qo(e.type,!0),e;default:return""}}function Ta(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case An:return"Fragment";case On:return"Portal";case Ea:return"Profiler";case Fl:return"StrictMode";case Na:return"Suspense";case Ra:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Md:return(e.displayName||"Context")+".Consumer";case Pd:return(e._context.displayName||"Context")+".Provider";case Bl:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Ul:return t=e.displayName||null,t!==null?t:Ta(e.type)||"Memo";case Pr:t=e._payload,e=e._init;try{return Ta(e(t))}catch{}}return null}function Lp(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Ta(t);case 8:return t===Fl?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Gr(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Fd(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Op(e){var t=Fd(e)?"checked":"value",r=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),n=""+e[t];if(!e.hasOwnProperty(t)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var i=r.get,s=r.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(o){n=""+o,s.call(this,o)}}),Object.defineProperty(e,t,{enumerable:r.enumerable}),{getValue:function(){return n},setValue:function(o){n=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function fs(e){e._valueTracker||(e._valueTracker=Op(e))}function Bd(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var r=t.getValue(),n="";return e&&(n=Fd(e)?e.checked?"true":"false":e.value),e=n,e!==r?(t.setValue(e),!0):!1}function Zs(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function za(e,t){var r=t.checked;return Me({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??e._wrapperState.initialChecked})}function Bu(e,t){var r=t.defaultValue==null?"":t.defaultValue,n=t.checked!=null?t.checked:t.defaultChecked;r=Gr(t.value!=null?t.value:r),e._wrapperState={initialChecked:n,initialValue:r,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Ud(e,t){t=t.checked,t!=null&&Dl(e,"checked",t,!1)}function Ia(e,t){Ud(e,t);var r=Gr(t.value),n=t.type;if(r!=null)n==="number"?(r===0&&e.value===""||e.value!=r)&&(e.value=""+r):e.value!==""+r&&(e.value=""+r);else if(n==="submit"||n==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?ja(e,t.type,r):t.hasOwnProperty("defaultValue")&&ja(e,t.type,Gr(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Uu(e,t,r){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var n=t.type;if(!(n!=="submit"&&n!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,r||t===e.value||(e.value=t),e.defaultValue=t}r=e.name,r!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,r!==""&&(e.name=r)}function ja(e,t,r){(t!=="number"||Zs(e.ownerDocument)!==e)&&(r==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+r&&(e.defaultValue=""+r))}var Ci=Array.isArray;function Kn(e,t,r,n){if(e=e.options,t){t={};for(var i=0;i"+t.valueOf().toString()+"",t=hs.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Bi(e,t){if(t){var r=e.firstChild;if(r&&r===e.lastChild&&r.nodeType===3){r.nodeValue=t;return}}e.textContent=t}var Ti={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Ap=["Webkit","ms","Moz","O"];Object.keys(Ti).forEach(function(e){Ap.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Ti[t]=Ti[e]})});function Hd(e,t,r){return t==null||typeof t=="boolean"||t===""?"":r||typeof t!="number"||t===0||Ti.hasOwnProperty(e)&&Ti[e]?(""+t).trim():t+"px"}function qd(e,t){e=e.style;for(var r in t)if(t.hasOwnProperty(r)){var n=r.indexOf("--")===0,i=Hd(r,t[r],n);r==="float"&&(r="cssFloat"),n?e.setProperty(r,i):e[r]=i}}var Pp=Me({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Aa(e,t){if(t){if(Pp[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(se(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(se(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(se(61))}if(t.style!=null&&typeof t.style!="object")throw Error(se(62))}}function Pa(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Ma=null;function $l(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Da=null,Yn=null,Zn=null;function Vu(e){if(e=os(e)){if(typeof Da!="function")throw Error(se(280));var t=e.stateNode;t&&(t=Eo(t),Da(e.stateNode,e.type,t))}}function Kd(e){Yn?Zn?Zn.push(e):Zn=[e]:Yn=e}function Yd(){if(Yn){var e=Yn,t=Zn;if(Zn=Yn=null,Vu(e),t)for(e=0;e>>=0,e===0?32:31-(Kp(e)/Yp|0)|0}var ps=64,ms=4194304;function Ei(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Js(e,t){var r=e.pendingLanes;if(r===0)return 0;var n=0,i=e.suspendedLanes,s=e.pingedLanes,o=r&268435455;if(o!==0){var a=o&~i;a!==0?n=Ei(a):(s&=o,s!==0&&(n=Ei(s)))}else o=r&~i,o!==0?n=Ei(o):s!==0&&(n=Ei(s));if(n===0)return 0;if(t!==0&&t!==n&&!(t&i)&&(i=n&-n,s=t&-t,i>=s||i===16&&(s&4194240)!==0))return t;if(n&4&&(n|=r&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=n;0r;r++)t.push(e);return t}function is(e,t,r){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Vt(t),e[t]=r}function Gp(e,t){var r=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var n=e.eventTimes;for(e=e.expirationTimes;0=Ii),Ju=" ",ec=!1;function mf(e,t){switch(e){case"keyup":return Em.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function gf(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Pn=!1;function Rm(e,t){switch(e){case"compositionend":return gf(t);case"keypress":return t.which!==32?null:(ec=!0,Ju);case"textInput":return e=t.data,e===Ju&&ec?null:e;default:return null}}function Tm(e,t){if(Pn)return e==="compositionend"||!Xl&&mf(e,t)?(e=hf(),Ps=Kl=Ur=null,Pn=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:r,offset:t-e};e=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=ic(r)}}function xf(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?xf(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function _f(){for(var e=window,t=Zs();t instanceof e.HTMLIFrameElement;){try{var r=typeof t.contentWindow.location.href=="string"}catch{r=!1}if(r)e=t.contentWindow;else break;t=Zs(e.document)}return t}function Ql(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Dm(e){var t=_f(),r=e.focusedElem,n=e.selectionRange;if(t!==r&&r&&r.ownerDocument&&xf(r.ownerDocument.documentElement,r)){if(n!==null&&Ql(r)){if(t=n.start,e=n.end,e===void 0&&(e=t),"selectionStart"in r)r.selectionStart=t,r.selectionEnd=Math.min(e,r.value.length);else if(e=(t=r.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var i=r.textContent.length,s=Math.min(n.start,i);n=n.end===void 0?s:Math.min(n.end,i),!e.extend&&s>n&&(i=n,n=s,s=i),i=sc(r,s);var o=sc(r,n);i&&o&&(e.rangeCount!==1||e.anchorNode!==i.node||e.anchorOffset!==i.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(i.node,i.offset),e.removeAllRanges(),s>n?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=r;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof r.focus=="function"&&r.focus(),r=0;r=document.documentMode,Mn=null,Va=null,Li=null,Ha=!1;function oc(e,t,r){var n=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;Ha||Mn==null||Mn!==Zs(n)||(n=Mn,"selectionStart"in n&&Ql(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),Li&&qi(Li,n)||(Li=n,n=ro(Va,"onSelect"),0Bn||(e.current=Qa[Bn],Qa[Bn]=null,Bn--)}function Ne(e,t){Bn++,Qa[Bn]=e.current,e.current=t}var Jr={},rt=tn(Jr),ft=tn(!1),yn=Jr;function ti(e,t){var r=e.type.contextTypes;if(!r)return Jr;var n=e.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===t)return n.__reactInternalMemoizedMaskedChildContext;var i={},s;for(s in r)i[s]=t[s];return n&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function ht(e){return e=e.childContextTypes,e!=null}function io(){je(ft),je(rt)}function hc(e,t,r){if(rt.current!==Jr)throw Error(se(168));Ne(rt,t),Ne(ft,r)}function zf(e,t,r){var n=e.stateNode;if(t=t.childContextTypes,typeof n.getChildContext!="function")return r;n=n.getChildContext();for(var i in n)if(!(i in t))throw Error(se(108,Lp(e)||"Unknown",i));return Me({},r,n)}function so(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Jr,yn=rt.current,Ne(rt,e),Ne(ft,ft.current),!0}function pc(e,t,r){var n=e.stateNode;if(!n)throw Error(se(169));r?(e=zf(e,t,yn),n.__reactInternalMemoizedMergedChildContext=e,je(ft),je(rt),Ne(rt,e)):je(ft),Ne(ft,r)}var wr=null,No=!1,oa=!1;function If(e){wr===null?wr=[e]:wr.push(e)}function Xm(e){No=!0,If(e)}function rn(){if(!oa&&wr!==null){oa=!0;var e=0,t=Ce;try{var r=wr;for(Ce=1;e>=o,i-=o,_r=1<<32-Vt(t)+i|r<O?(I=z,z=null):I=z.sibling;var P=v(c,z,g[O],S);if(P===null){z===null&&(z=I);break}e&&z&&P.alternate===null&&t(c,z),d=s(P,d,O),R===null?b=P:R.sibling=P,R=P,z=I}if(O===g.length)return r(c,z),Oe&&ln(c,O),b;if(z===null){for(;OO?(I=z,z=null):I=z.sibling;var re=v(c,z,P.value,S);if(re===null){z===null&&(z=I);break}e&&z&&re.alternate===null&&t(c,z),d=s(re,d,O),R===null?b=re:R.sibling=re,R=re,z=I}if(P.done)return r(c,z),Oe&&ln(c,O),b;if(z===null){for(;!P.done;O++,P=g.next())P=y(c,P.value,S),P!==null&&(d=s(P,d,O),R===null?b=P:R.sibling=P,R=P);return Oe&&ln(c,O),b}for(z=n(c,z);!P.done;O++,P=g.next())P=p(z,c,O,P.value,S),P!==null&&(e&&P.alternate!==null&&z.delete(P.key===null?O:P.key),d=s(P,d,O),R===null?b=P:R.sibling=P,R=P);return e&&z.forEach(function(T){return t(c,T)}),Oe&&ln(c,O),b}function _(c,d,g,S){if(typeof g=="object"&&g!==null&&g.type===An&&g.key===null&&(g=g.props.children),typeof g=="object"&&g!==null){switch(g.$$typeof){case ds:e:{for(var b=g.key,R=d;R!==null;){if(R.key===b){if(b=g.type,b===An){if(R.tag===7){r(c,R.sibling),d=i(R,g.props.children),d.return=c,c=d;break e}}else if(R.elementType===b||typeof b=="object"&&b!==null&&b.$$typeof===Pr&&yc(b)===R.type){r(c,R.sibling),d=i(R,g.props),d.ref=xi(c,R,g),d.return=c,c=d;break e}r(c,R);break}else t(c,R);R=R.sibling}g.type===An?(d=gn(g.props.children,c.mode,S,g.key),d.return=c,c=d):(S=Vs(g.type,g.key,g.props,null,c.mode,S),S.ref=xi(c,d,g),S.return=c,c=S)}return o(c);case On:e:{for(R=g.key;d!==null;){if(d.key===R)if(d.tag===4&&d.stateNode.containerInfo===g.containerInfo&&d.stateNode.implementation===g.implementation){r(c,d.sibling),d=i(d,g.children||[]),d.return=c,c=d;break e}else{r(c,d);break}else t(c,d);d=d.sibling}d=pa(g,c.mode,S),d.return=c,c=d}return o(c);case Pr:return R=g._init,_(c,d,R(g._payload),S)}if(Ci(g))return x(c,d,g,S);if(mi(g))return u(c,d,g,S);ks(c,g)}return typeof g=="string"&&g!==""||typeof g=="number"?(g=""+g,d!==null&&d.tag===6?(r(c,d.sibling),d=i(d,g),d.return=c,c=d):(r(c,d),d=ha(g,c.mode,S),d.return=c,c=d),o(c)):r(c,d)}return _}var ni=Af(!0),Pf=Af(!1),lo=tn(null),uo=null,Wn=null,tu=null;function ru(){tu=Wn=uo=null}function nu(e){var t=lo.current;je(lo),e._currentValue=t}function el(e,t,r){for(;e!==null;){var n=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,n!==null&&(n.childLanes|=t)):n!==null&&(n.childLanes&t)!==t&&(n.childLanes|=t),e===r)break;e=e.return}}function Qn(e,t){uo=e,tu=Wn=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(dt=!0),e.firstContext=null)}function At(e){var t=e._currentValue;if(tu!==e)if(e={context:e,memoizedValue:t,next:null},Wn===null){if(uo===null)throw Error(se(308));Wn=e,uo.dependencies={lanes:0,firstContext:e}}else Wn=Wn.next=e;return t}var hn=null;function iu(e){hn===null?hn=[e]:hn.push(e)}function Mf(e,t,r,n){var i=t.interleaved;return i===null?(r.next=r,iu(t)):(r.next=i.next,i.next=r),t.interleaved=r,Er(e,n)}function Er(e,t){e.lanes|=t;var r=e.alternate;for(r!==null&&(r.lanes|=t),r=e,e=e.return;e!==null;)e.childLanes|=t,r=e.alternate,r!==null&&(r.childLanes|=t),r=e,e=e.return;return r.tag===3?r.stateNode:null}var Mr=!1;function su(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Df(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Sr(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Kr(e,t,r){var n=e.updateQueue;if(n===null)return null;if(n=n.shared,Se&2){var i=n.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),n.pending=t,Er(e,r)}return i=n.interleaved,i===null?(t.next=t,iu(n)):(t.next=i.next,i.next=t),n.interleaved=t,Er(e,r)}function Ds(e,t,r){if(t=t.updateQueue,t!==null&&(t=t.shared,(r&4194240)!==0)){var n=t.lanes;n&=e.pendingLanes,r|=n,t.lanes=r,Vl(e,r)}}function vc(e,t){var r=e.updateQueue,n=e.alternate;if(n!==null&&(n=n.updateQueue,r===n)){var i=null,s=null;if(r=r.firstBaseUpdate,r!==null){do{var o={eventTime:r.eventTime,lane:r.lane,tag:r.tag,payload:r.payload,callback:r.callback,next:null};s===null?i=s=o:s=s.next=o,r=r.next}while(r!==null);s===null?i=s=t:s=s.next=t}else i=s=t;r={baseState:n.baseState,firstBaseUpdate:i,lastBaseUpdate:s,shared:n.shared,effects:n.effects},e.updateQueue=r;return}e=r.lastBaseUpdate,e===null?r.firstBaseUpdate=t:e.next=t,r.lastBaseUpdate=t}function co(e,t,r,n){var i=e.updateQueue;Mr=!1;var s=i.firstBaseUpdate,o=i.lastBaseUpdate,a=i.shared.pending;if(a!==null){i.shared.pending=null;var l=a,h=l.next;l.next=null,o===null?s=h:o.next=h,o=l;var w=e.alternate;w!==null&&(w=w.updateQueue,a=w.lastBaseUpdate,a!==o&&(a===null?w.firstBaseUpdate=h:a.next=h,w.lastBaseUpdate=l))}if(s!==null){var y=i.baseState;o=0,w=h=l=null,a=s;do{var v=a.lane,p=a.eventTime;if((n&v)===v){w!==null&&(w=w.next={eventTime:p,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var x=e,u=a;switch(v=t,p=r,u.tag){case 1:if(x=u.payload,typeof x=="function"){y=x.call(p,y,v);break e}y=x;break e;case 3:x.flags=x.flags&-65537|128;case 0:if(x=u.payload,v=typeof x=="function"?x.call(p,y,v):x,v==null)break e;y=Me({},y,v);break e;case 2:Mr=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,v=i.effects,v===null?i.effects=[a]:v.push(a))}else p={eventTime:p,lane:v,tag:a.tag,payload:a.payload,callback:a.callback,next:null},w===null?(h=w=p,l=y):w=w.next=p,o|=v;if(a=a.next,a===null){if(a=i.shared.pending,a===null)break;v=a,a=v.next,v.next=null,i.lastBaseUpdate=v,i.shared.pending=null}}while(!0);if(w===null&&(l=y),i.baseState=l,i.firstBaseUpdate=h,i.lastBaseUpdate=w,t=i.shared.interleaved,t!==null){i=t;do o|=i.lane,i=i.next;while(i!==t)}else s===null&&(i.shared.lanes=0);xn|=o,e.lanes=o,e.memoizedState=y}}function wc(e,t,r){if(e=t.effects,t.effects=null,e!==null)for(t=0;tr?r:4,e(!0);var n=la.transition;la.transition={};try{e(!1),t()}finally{Ce=r,la.transition=n}}function th(){return Pt().memoizedState}function e0(e,t,r){var n=Zr(e);if(r={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null},rh(e))nh(t,r);else if(r=Mf(e,t,r,n),r!==null){var i=at();Ht(r,e,n,i),ih(r,t,n)}}function t0(e,t,r){var n=Zr(e),i={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null};if(rh(e))nh(t,i);else{var s=e.alternate;if(e.lanes===0&&(s===null||s.lanes===0)&&(s=t.lastRenderedReducer,s!==null))try{var o=t.lastRenderedState,a=s(o,r);if(i.hasEagerState=!0,i.eagerState=a,qt(a,o)){var l=t.interleaved;l===null?(i.next=i,iu(t)):(i.next=l.next,l.next=i),t.interleaved=i;return}}catch{}finally{}r=Mf(e,t,i,n),r!==null&&(i=at(),Ht(r,e,n,i),ih(r,t,n))}}function rh(e){var t=e.alternate;return e===Pe||t!==null&&t===Pe}function nh(e,t){Oi=ho=!0;var r=e.pending;r===null?t.next=t:(t.next=r.next,r.next=t),e.pending=t}function ih(e,t,r){if(r&4194240){var n=t.lanes;n&=e.pendingLanes,r|=n,t.lanes=r,Vl(e,r)}}var po={readContext:At,useCallback:Je,useContext:Je,useEffect:Je,useImperativeHandle:Je,useInsertionEffect:Je,useLayoutEffect:Je,useMemo:Je,useReducer:Je,useRef:Je,useState:Je,useDebugValue:Je,useDeferredValue:Je,useTransition:Je,useMutableSource:Je,useSyncExternalStore:Je,useId:Je,unstable_isNewReconciler:!1},r0={readContext:At,useCallback:function(e,t){return er().memoizedState=[e,t===void 0?null:t],e},useContext:At,useEffect:_c,useImperativeHandle:function(e,t,r){return r=r!=null?r.concat([e]):null,Bs(4194308,4,Xf.bind(null,t,e),r)},useLayoutEffect:function(e,t){return Bs(4194308,4,e,t)},useInsertionEffect:function(e,t){return Bs(4,2,e,t)},useMemo:function(e,t){var r=er();return t=t===void 0?null:t,e=e(),r.memoizedState=[e,t],e},useReducer:function(e,t,r){var n=er();return t=r!==void 0?r(t):t,n.memoizedState=n.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},n.queue=e,e=e.dispatch=e0.bind(null,Pe,e),[n.memoizedState,e]},useRef:function(e){var t=er();return e={current:e},t.memoizedState=e},useState:xc,useDebugValue:hu,useDeferredValue:function(e){return er().memoizedState=e},useTransition:function(){var e=xc(!1),t=e[0];return e=Jm.bind(null,e[1]),er().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,r){var n=Pe,i=er();if(Oe){if(r===void 0)throw Error(se(407));r=r()}else{if(r=t(),Ke===null)throw Error(se(349));wn&30||$f(n,t,r)}i.memoizedState=r;var s={value:r,getSnapshot:t};return i.queue=s,_c(Vf.bind(null,n,s,e),[e]),n.flags|=2048,es(9,Wf.bind(null,n,s,r,t),void 0,null),r},useId:function(){var e=er(),t=Ke.identifierPrefix;if(Oe){var r=kr,n=_r;r=(n&~(1<<32-Vt(n)-1)).toString(32)+r,t=":"+t+"R"+r,r=Gi++,0<\/script>",e=e.removeChild(e.firstChild)):typeof n.is=="string"?e=o.createElement(r,{is:n.is}):(e=o.createElement(r),r==="select"&&(o=e,n.multiple?o.multiple=!0:n.size&&(o.size=n.size))):e=o.createElementNS(e,r),e[tr]=t,e[Zi]=n,ph(e,t,!1,!1),t.stateNode=e;e:{switch(o=Pa(r,n),r){case"dialog":Ie("cancel",e),Ie("close",e),i=n;break;case"iframe":case"object":case"embed":Ie("load",e),i=n;break;case"video":case"audio":for(i=0;ioi&&(t.flags|=128,n=!0,_i(s,!1),t.lanes=4194304)}else{if(!n)if(e=fo(o),e!==null){if(t.flags|=128,n=!0,r=e.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),_i(s,!0),s.tail===null&&s.tailMode==="hidden"&&!o.alternate&&!Oe)return et(t),null}else 2*Fe()-s.renderingStartTime>oi&&r!==1073741824&&(t.flags|=128,n=!0,_i(s,!1),t.lanes=4194304);s.isBackwards?(o.sibling=t.child,t.child=o):(r=s.last,r!==null?r.sibling=o:t.child=o,s.last=o)}return s.tail!==null?(t=s.tail,s.rendering=t,s.tail=t.sibling,s.renderingStartTime=Fe(),t.sibling=null,r=Ae.current,Ne(Ae,n?r&1|2:r&1),t):(et(t),null);case 22:case 23:return wu(),n=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==n&&(t.flags|=8192),n&&t.mode&1?vt&1073741824&&(et(t),t.subtreeFlags&6&&(t.flags|=8192)):et(t),null;case 24:return null;case 25:return null}throw Error(se(156,t.tag))}function c0(e,t){switch(Jl(t),t.tag){case 1:return ht(t.type)&&io(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return ii(),je(ft),je(rt),lu(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return au(t),null;case 13:if(je(Ae),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(se(340));ri()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return je(Ae),null;case 4:return ii(),null;case 10:return nu(t.type._context),null;case 22:case 23:return wu(),null;case 24:return null;default:return null}}var bs=!1,tt=!1,d0=typeof WeakSet=="function"?WeakSet:Set,fe=null;function Vn(e,t){var r=e.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(n){De(e,t,n)}else r.current=null}function ul(e,t,r){try{r()}catch(n){De(e,t,n)}}var jc=!1;function f0(e,t){if(qa=eo,e=_f(),Ql(e)){if("selectionStart"in e)var r={start:e.selectionStart,end:e.selectionEnd};else e:{r=(r=e.ownerDocument)&&r.defaultView||window;var n=r.getSelection&&r.getSelection();if(n&&n.rangeCount!==0){r=n.anchorNode;var i=n.anchorOffset,s=n.focusNode;n=n.focusOffset;try{r.nodeType,s.nodeType}catch{r=null;break e}var o=0,a=-1,l=-1,h=0,w=0,y=e,v=null;t:for(;;){for(var p;y!==r||i!==0&&y.nodeType!==3||(a=o+i),y!==s||n!==0&&y.nodeType!==3||(l=o+n),y.nodeType===3&&(o+=y.nodeValue.length),(p=y.firstChild)!==null;)v=y,y=p;for(;;){if(y===e)break t;if(v===r&&++h===i&&(a=o),v===s&&++w===n&&(l=o),(p=y.nextSibling)!==null)break;y=v,v=y.parentNode}y=p}r=a===-1||l===-1?null:{start:a,end:l}}else r=null}r=r||{start:0,end:0}}else r=null;for(Ka={focusedElem:e,selectionRange:r},eo=!1,fe=t;fe!==null;)if(t=fe,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,fe=e;else for(;fe!==null;){t=fe;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var u=x.memoizedProps,_=x.memoizedState,c=t.stateNode,d=c.getSnapshotBeforeUpdate(t.elementType===t.type?u:Bt(t.type,u),_);c.__reactInternalSnapshotBeforeUpdate=d}break;case 3:var g=t.stateNode.containerInfo;g.nodeType===1?g.textContent="":g.nodeType===9&&g.documentElement&&g.removeChild(g.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(se(163))}}catch(S){De(t,t.return,S)}if(e=t.sibling,e!==null){e.return=t.return,fe=e;break}fe=t.return}return x=jc,jc=!1,x}function Ai(e,t,r){var n=t.updateQueue;if(n=n!==null?n.lastEffect:null,n!==null){var i=n=n.next;do{if((i.tag&e)===e){var s=i.destroy;i.destroy=void 0,s!==void 0&&ul(t,r,s)}i=i.next}while(i!==n)}}function zo(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var r=t=t.next;do{if((r.tag&e)===e){var n=r.create;r.destroy=n()}r=r.next}while(r!==t)}}function cl(e){var t=e.ref;if(t!==null){var r=e.stateNode;switch(e.tag){case 5:e=r;break;default:e=r}typeof t=="function"?t(e):t.current=e}}function yh(e){var t=e.alternate;t!==null&&(e.alternate=null,yh(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[tr],delete t[Zi],delete t[Xa],delete t[Ym],delete t[Zm])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function vh(e){return e.tag===5||e.tag===3||e.tag===4}function Lc(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||vh(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function dl(e,t,r){var n=e.tag;if(n===5||n===6)e=e.stateNode,t?r.nodeType===8?r.parentNode.insertBefore(e,t):r.insertBefore(e,t):(r.nodeType===8?(t=r.parentNode,t.insertBefore(e,r)):(t=r,t.appendChild(e)),r=r._reactRootContainer,r!=null||t.onclick!==null||(t.onclick=no));else if(n!==4&&(e=e.child,e!==null))for(dl(e,t,r),e=e.sibling;e!==null;)dl(e,t,r),e=e.sibling}function fl(e,t,r){var n=e.tag;if(n===5||n===6)e=e.stateNode,t?r.insertBefore(e,t):r.appendChild(e);else if(n!==4&&(e=e.child,e!==null))for(fl(e,t,r),e=e.sibling;e!==null;)fl(e,t,r),e=e.sibling}var Ye=null,Ut=!1;function Ar(e,t,r){for(r=r.child;r!==null;)wh(e,t,r),r=r.sibling}function wh(e,t,r){if(nr&&typeof nr.onCommitFiberUnmount=="function")try{nr.onCommitFiberUnmount(ko,r)}catch{}switch(r.tag){case 5:tt||Vn(r,t);case 6:var n=Ye,i=Ut;Ye=null,Ar(e,t,r),Ye=n,Ut=i,Ye!==null&&(Ut?(e=Ye,r=r.stateNode,e.nodeType===8?e.parentNode.removeChild(r):e.removeChild(r)):Ye.removeChild(r.stateNode));break;case 18:Ye!==null&&(Ut?(e=Ye,r=r.stateNode,e.nodeType===8?sa(e.parentNode,r):e.nodeType===1&&sa(e,r),Vi(e)):sa(Ye,r.stateNode));break;case 4:n=Ye,i=Ut,Ye=r.stateNode.containerInfo,Ut=!0,Ar(e,t,r),Ye=n,Ut=i;break;case 0:case 11:case 14:case 15:if(!tt&&(n=r.updateQueue,n!==null&&(n=n.lastEffect,n!==null))){i=n=n.next;do{var s=i,o=s.destroy;s=s.tag,o!==void 0&&(s&2||s&4)&&ul(r,t,o),i=i.next}while(i!==n)}Ar(e,t,r);break;case 1:if(!tt&&(Vn(r,t),n=r.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=r.memoizedProps,n.state=r.memoizedState,n.componentWillUnmount()}catch(a){De(r,t,a)}Ar(e,t,r);break;case 21:Ar(e,t,r);break;case 22:r.mode&1?(tt=(n=tt)||r.memoizedState!==null,Ar(e,t,r),tt=n):Ar(e,t,r);break;default:Ar(e,t,r)}}function Oc(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var r=e.stateNode;r===null&&(r=e.stateNode=new d0),t.forEach(function(n){var i=_0.bind(null,e,n);r.has(n)||(r.add(n),n.then(i,i))})}}function Ft(e,t){var r=t.deletions;if(r!==null)for(var n=0;ni&&(i=o),n&=~s}if(n=i,n=Fe()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*p0(n/1960))-n,10e?16:e,$r===null)var n=!1;else{if(e=$r,$r=null,yo=0,Se&6)throw Error(se(331));var i=Se;for(Se|=4,fe=e.current;fe!==null;){var s=fe,o=s.child;if(fe.flags&16){var a=s.deletions;if(a!==null){for(var l=0;lFe()-yu?mn(e,0):gu|=r),pt(e,t)}function Nh(e,t){t===0&&(e.mode&1?(t=ms,ms<<=1,!(ms&130023424)&&(ms=4194304)):t=1);var r=at();e=Er(e,t),e!==null&&(is(e,t,r),pt(e,r))}function x0(e){var t=e.memoizedState,r=0;t!==null&&(r=t.retryLane),Nh(e,r)}function _0(e,t){var r=0;switch(e.tag){case 13:var n=e.stateNode,i=e.memoizedState;i!==null&&(r=i.retryLane);break;case 19:n=e.stateNode;break;default:throw Error(se(314))}n!==null&&n.delete(t),Nh(e,r)}var Rh;Rh=function(e,t,r){if(e!==null)if(e.memoizedProps!==t.pendingProps||ft.current)dt=!0;else{if(!(e.lanes&r)&&!(t.flags&128))return dt=!1,l0(e,t,r);dt=!!(e.flags&131072)}else dt=!1,Oe&&t.flags&1048576&&jf(t,ao,t.index);switch(t.lanes=0,t.tag){case 2:var n=t.type;Us(e,t),e=t.pendingProps;var i=ti(t,rt.current);Qn(t,r),i=cu(null,t,n,e,i,r);var s=du();return t.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,ht(n)?(s=!0,so(t)):s=!1,t.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,su(t),i.updater=To,t.stateNode=i,i._reactInternals=t,rl(t,n,e,r),t=sl(null,t,n,!0,s,r)):(t.tag=0,Oe&&s&&Gl(t),ot(null,t,i,r),t=t.child),t;case 16:n=t.elementType;e:{switch(Us(e,t),e=t.pendingProps,i=n._init,n=i(n._payload),t.type=n,i=t.tag=S0(n),e=Bt(n,e),i){case 0:t=il(null,t,n,e,r);break e;case 1:t=Tc(null,t,n,e,r);break e;case 11:t=Nc(null,t,n,e,r);break e;case 14:t=Rc(null,t,n,Bt(n.type,e),r);break e}throw Error(se(306,n,""))}return t;case 0:return n=t.type,i=t.pendingProps,i=t.elementType===n?i:Bt(n,i),il(e,t,n,i,r);case 1:return n=t.type,i=t.pendingProps,i=t.elementType===n?i:Bt(n,i),Tc(e,t,n,i,r);case 3:e:{if(dh(t),e===null)throw Error(se(387));n=t.pendingProps,s=t.memoizedState,i=s.element,Df(e,t),co(t,n,null,r);var o=t.memoizedState;if(n=o.element,s.isDehydrated)if(s={element:n,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=s,t.memoizedState=s,t.flags&256){i=si(Error(se(423)),t),t=zc(e,t,n,r,i);break e}else if(n!==i){i=si(Error(se(424)),t),t=zc(e,t,n,r,i);break e}else for(wt=qr(t.stateNode.containerInfo.firstChild),xt=t,Oe=!0,Wt=null,r=Pf(t,null,n,r),t.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(ri(),n===i){t=Nr(e,t,r);break e}ot(e,t,n,r)}t=t.child}return t;case 5:return Ff(t),e===null&&Ja(t),n=t.type,i=t.pendingProps,s=e!==null?e.memoizedProps:null,o=i.children,Ya(n,i)?o=null:s!==null&&Ya(n,s)&&(t.flags|=32),ch(e,t),ot(e,t,o,r),t.child;case 6:return e===null&&Ja(t),null;case 13:return fh(e,t,r);case 4:return ou(t,t.stateNode.containerInfo),n=t.pendingProps,e===null?t.child=ni(t,null,n,r):ot(e,t,n,r),t.child;case 11:return n=t.type,i=t.pendingProps,i=t.elementType===n?i:Bt(n,i),Nc(e,t,n,i,r);case 7:return ot(e,t,t.pendingProps,r),t.child;case 8:return ot(e,t,t.pendingProps.children,r),t.child;case 12:return ot(e,t,t.pendingProps.children,r),t.child;case 10:e:{if(n=t.type._context,i=t.pendingProps,s=t.memoizedProps,o=i.value,Ne(lo,n._currentValue),n._currentValue=o,s!==null)if(qt(s.value,o)){if(s.children===i.children&&!ft.current){t=Nr(e,t,r);break e}}else for(s=t.child,s!==null&&(s.return=t);s!==null;){var a=s.dependencies;if(a!==null){o=s.child;for(var l=a.firstContext;l!==null;){if(l.context===n){if(s.tag===1){l=Sr(-1,r&-r),l.tag=2;var h=s.updateQueue;if(h!==null){h=h.shared;var w=h.pending;w===null?l.next=l:(l.next=w.next,w.next=l),h.pending=l}}s.lanes|=r,l=s.alternate,l!==null&&(l.lanes|=r),el(s.return,r,t),a.lanes|=r;break}l=l.next}}else if(s.tag===10)o=s.type===t.type?null:s.child;else if(s.tag===18){if(o=s.return,o===null)throw Error(se(341));o.lanes|=r,a=o.alternate,a!==null&&(a.lanes|=r),el(o,r,t),o=s.sibling}else o=s.child;if(o!==null)o.return=s;else for(o=s;o!==null;){if(o===t){o=null;break}if(s=o.sibling,s!==null){s.return=o.return,o=s;break}o=o.return}s=o}ot(e,t,i.children,r),t=t.child}return t;case 9:return i=t.type,n=t.pendingProps.children,Qn(t,r),i=At(i),n=n(i),t.flags|=1,ot(e,t,n,r),t.child;case 14:return n=t.type,i=Bt(n,t.pendingProps),i=Bt(n.type,i),Rc(e,t,n,i,r);case 15:return lh(e,t,t.type,t.pendingProps,r);case 17:return n=t.type,i=t.pendingProps,i=t.elementType===n?i:Bt(n,i),Us(e,t),t.tag=1,ht(n)?(e=!0,so(t)):e=!1,Qn(t,r),sh(t,n,i),rl(t,n,i,r),sl(null,t,n,!0,e,r);case 19:return hh(e,t,r);case 22:return uh(e,t,r)}throw Error(se(156,t.tag))};function Th(e,t){return tf(e,t)}function k0(e,t,r,n){this.tag=e,this.key=r,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=n,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Lt(e,t,r,n){return new k0(e,t,r,n)}function _u(e){return e=e.prototype,!(!e||!e.isReactComponent)}function S0(e){if(typeof e=="function")return _u(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Bl)return 11;if(e===Ul)return 14}return 2}function Xr(e,t){var r=e.alternate;return r===null?(r=Lt(e.tag,t,e.key,e.mode),r.elementType=e.elementType,r.type=e.type,r.stateNode=e.stateNode,r.alternate=e,e.alternate=r):(r.pendingProps=t,r.type=e.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=e.flags&14680064,r.childLanes=e.childLanes,r.lanes=e.lanes,r.child=e.child,r.memoizedProps=e.memoizedProps,r.memoizedState=e.memoizedState,r.updateQueue=e.updateQueue,t=e.dependencies,r.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},r.sibling=e.sibling,r.index=e.index,r.ref=e.ref,r}function Vs(e,t,r,n,i,s){var o=2;if(n=e,typeof e=="function")_u(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case An:return gn(r.children,i,s,t);case Fl:o=8,i|=8;break;case Ea:return e=Lt(12,r,t,i|2),e.elementType=Ea,e.lanes=s,e;case Na:return e=Lt(13,r,t,i),e.elementType=Na,e.lanes=s,e;case Ra:return e=Lt(19,r,t,i),e.elementType=Ra,e.lanes=s,e;case Dd:return jo(r,i,s,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Pd:o=10;break e;case Md:o=9;break e;case Bl:o=11;break e;case Ul:o=14;break e;case Pr:o=16,n=null;break e}throw Error(se(130,e==null?e:typeof e,""))}return t=Lt(o,r,t,i),t.elementType=e,t.type=n,t.lanes=s,t}function gn(e,t,r,n){return e=Lt(7,e,n,t),e.lanes=r,e}function jo(e,t,r,n){return e=Lt(22,e,n,t),e.elementType=Dd,e.lanes=r,e.stateNode={isHidden:!1},e}function ha(e,t,r){return e=Lt(6,e,null,t),e.lanes=r,e}function pa(e,t,r){return t=Lt(4,e.children!==null?e.children:[],e.key,t),t.lanes=r,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function b0(e,t,r,n,i){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Yo(0),this.expirationTimes=Yo(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Yo(0),this.identifierPrefix=n,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function ku(e,t,r,n,i,s,o,a,l){return e=new b0(e,t,r,a,l),t===1?(t=1,s===!0&&(t|=8)):t=0,s=Lt(3,null,null,t),e.current=s,s.stateNode=e,s.memoizedState={element:n,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},su(s),e}function C0(e,t,r){var n=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Lh)}catch(e){console.error(e)}}Lh(),jd.exports=kt;var Oh=jd.exports,$c=Oh;ba.createRoot=$c.createRoot,ba.hydrateRoot=$c.hydrateRoot;const or=Object.create(null);or.open="0";or.close="1";or.ping="2";or.pong="3";or.message="4";or.upgrade="5";or.noop="6";const Hs=Object.create(null);Object.keys(or).forEach(e=>{Hs[or[e]]=e});const yl={type:"error",data:"parser error"},Ah=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Ph=typeof ArrayBuffer=="function",Mh=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Eu=({type:e,data:t},r,n)=>Ah&&t instanceof Blob?r?n(t):Wc(t,n):Ph&&(t instanceof ArrayBuffer||Mh(t))?r?n(t):Wc(new Blob([t]),n):n(or[e]+(t||"")),Wc=(e,t)=>{const r=new FileReader;return r.onload=function(){const n=r.result.split(",")[1];t("b"+(n||""))},r.readAsDataURL(e)};function Vc(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let ma;function z0(e,t){if(Ah&&e.data instanceof Blob)return e.data.arrayBuffer().then(Vc).then(t);if(Ph&&(e.data instanceof ArrayBuffer||Mh(e.data)))return t(Vc(e.data));Eu(e,!1,r=>{ma||(ma=new TextEncoder),t(ma.encode(r))})}const Hc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ri=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,r=e.length,n,i=0,s,o,a,l;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const h=new ArrayBuffer(t),w=new Uint8Array(h);for(n=0;n>4,w[i++]=(o&15)<<4|a>>2,w[i++]=(a&3)<<6|l&63;return h},j0=typeof ArrayBuffer=="function",Nu=(e,t)=>{if(typeof e!="string")return{type:"message",data:Dh(e,t)};const r=e.charAt(0);return r==="b"?{type:"message",data:L0(e.substring(1),t)}:Hs[r]?e.length>1?{type:Hs[r],data:e.substring(1)}:{type:Hs[r]}:yl},L0=(e,t)=>{if(j0){const r=I0(e);return Dh(r,t)}else return{base64:!0,data:e}},Dh=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},Fh="",O0=(e,t)=>{const r=e.length,n=new Array(r);let i=0;e.forEach((s,o)=>{Eu(s,!1,a=>{n[o]=a,++i===r&&t(n.join(Fh))})})},A0=(e,t)=>{const r=e.split(Fh),n=[];for(let i=0;i{const n=r.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const s=new DataView(i.buffer);s.setUint8(0,126),s.setUint16(1,n)}else{i=new Uint8Array(9);const s=new DataView(i.buffer);s.setUint8(0,127),s.setBigUint64(1,BigInt(n))}e.data&&typeof e.data!="string"&&(i[0]|=128),t.enqueue(i),t.enqueue(r)})}})}let ga;function Ns(e){return e.reduce((t,r)=>t+r.length,0)}function Rs(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let n=0;for(let i=0;iMath.pow(2,21)-1){a.enqueue(yl);break}i=w*Math.pow(2,32)+h.getUint32(4),n=3}else{if(Ns(r)e){a.enqueue(yl);break}}}})}const Bh=4;function Ue(e){if(e)return D0(e)}function D0(e){for(var t in Ue.prototype)e[t]=Ue.prototype[t];return e}Ue.prototype.on=Ue.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};Ue.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this};Ue.prototype.off=Ue.prototype.removeListener=Ue.prototype.removeAllListeners=Ue.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var r=this._callbacks["$"+e];if(!r)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var n,i=0;iPromise.resolve().then(t):(t,r)=>r(t,0),It=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),F0="arraybuffer";function Uh(e,...t){return t.reduce((r,n)=>(e.hasOwnProperty(n)&&(r[n]=e[n]),r),{})}const B0=It.setTimeout,U0=It.clearTimeout;function Do(e,t){t.useNativeTimers?(e.setTimeoutFn=B0.bind(It),e.clearTimeoutFn=U0.bind(It)):(e.setTimeoutFn=It.setTimeout.bind(It),e.clearTimeoutFn=It.clearTimeout.bind(It))}const $0=1.33;function W0(e){return typeof e=="string"?V0(e):Math.ceil((e.byteLength||e.size)*$0)}function V0(e){let t=0,r=0;for(let n=0,i=e.length;n=57344?r+=3:(n++,r+=4);return r}function $h(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function H0(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}function q0(e){let t={},r=e.split("&");for(let n=0,i=r.length;n{this.readyState="paused",t()};if(this._polling||!this.writable){let n=0;this._polling&&(n++,this.once("pollComplete",function(){--n||r()})),this.writable||(n++,this.once("drain",function(){--n||r()}))}else r()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const r=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};A0(t,this.socket.binaryType).forEach(r),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,O0(t,r=>{this.doWrite(r,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",r=this.query||{};return this.opts.timestampRequests!==!1&&(r[this.opts.timestampParam]=$h()),!this.supportsBinary&&!r.sid&&(r.b64=1),this.createUri(t,r)}}let Wh=!1;try{Wh=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Z0=Wh;function X0(){}class Q0 extends Y0{constructor(t){if(super(t),typeof location<"u"){const r=location.protocol==="https:";let n=location.port;n||(n=r?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,r){const n=this.request({method:"POST",data:t});n.on("success",r),n.on("error",(i,s)=>{this.onError("xhr post error",i,s)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(r,n)=>{this.onError("xhr poll error",r,n)}),this.pollXhr=t}}class sr extends Ue{constructor(t,r,n){super(),this.createRequest=t,Do(this,n),this._opts=n,this._method=n.method||"GET",this._uri=r,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var t;const r=Uh(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(r);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&n.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var i;n.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},n.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=sr.requestsCount++,sr.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=X0,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete sr.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}sr.requestsCount=0;sr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",qc);else if(typeof addEventListener=="function"){const e="onpagehide"in It?"pagehide":"unload";addEventListener(e,qc,!1)}}function qc(){for(let e in sr.requests)sr.requests.hasOwnProperty(e)&&sr.requests[e].abort()}const G0=function(){const e=Vh({xdomain:!1});return e&&e.responseType!==null}();class J0 extends Q0{constructor(t){super(t);const r=t&&t.forceBase64;this.supportsBinary=G0&&!r}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new sr(Vh,this.uri(),t)}}function Vh(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||Z0))return new XMLHttpRequest}catch{}if(!t)try{return new It[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Hh=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class eg extends Ru{get name(){return"websocket"}doOpen(){const t=this.uri(),r=this.opts.protocols,n=Hh?{}:Uh(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,r,n)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let r=0;r{try{this.doWrite(n,s)}catch{}i&&Mo(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",r=this.query||{};return this.opts.timestampRequests&&(r[this.opts.timestampParam]=$h()),this.supportsBinary||(r.b64=1),this.createUri(t,r)}}const ya=It.WebSocket||It.MozWebSocket;class tg extends eg{createSocket(t,r,n){return Hh?new ya(t,r,n):r?new ya(t,r):new ya(t)}doWrite(t,r){this.ws.send(r)}}class rg extends Ru{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const r=M0(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(r).getReader(),i=P0();i.readable.pipeTo(t.writable),this._writer=i.writable.getWriter();const s=()=>{n.read().then(({done:a,value:l})=>{a||(this.onPacket(l),s())}).catch(a=>{})};s();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let r=0;r{i&&Mo(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const ng={websocket:tg,webtransport:rg,polling:J0},ig=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,sg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function vl(e){if(e.length>8e3)throw"URI too long";const t=e,r=e.indexOf("["),n=e.indexOf("]");r!=-1&&n!=-1&&(e=e.substring(0,r)+e.substring(r,n).replace(/:/g,";")+e.substring(n,e.length));let i=ig.exec(e||""),s={},o=14;for(;o--;)s[sg[o]]=i[o]||"";return r!=-1&&n!=-1&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=og(s,s.path),s.queryKey=ag(s,s.query),s}function og(e,t){const r=/\/{2,9}/g,n=t.replace(r,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&n.splice(0,1),t.slice(-1)=="/"&&n.splice(n.length-1,1),n}function ag(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,s){i&&(r[i]=s)}),r}const wl=typeof addEventListener=="function"&&typeof removeEventListener=="function",qs=[];wl&&addEventListener("offline",()=>{qs.forEach(e=>e())},!1);class Qr extends Ue{constructor(t,r){if(super(),this.binaryType=F0,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(r=t,t=null),t){const n=vl(t);r.hostname=n.host,r.secure=n.protocol==="https"||n.protocol==="wss",r.port=n.port,n.query&&(r.query=n.query)}else r.host&&(r.hostname=vl(r.host).host);Do(this,r),this.secure=r.secure!=null?r.secure:typeof location<"u"&&location.protocol==="https:",r.hostname&&!r.port&&(r.port=this.secure?"443":"80"),this.hostname=r.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=r.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},r.transports.forEach(n=>{const i=n.prototype.name;this.transports.push(i),this._transportsByName[i]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},r),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=q0(this.opts.query)),wl&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},qs.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const r=Object.assign({},this.opts.query);r.EIO=Bh,r.transport=t,this.id&&(r.sid=this.id);const n=Object.assign({},this.opts,{query:r,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&Qr.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const r=this.createTransport(t);r.open(),this.setTransport(r)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",r=>this._onClose("transport close",r))}onOpen(){this.readyState="open",Qr.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const r=new Error("server error");r.code=t.data,this._onError(r);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let r=1;for(let n=0;n0&&r>this._maxPayload)return this.writeBuffer.slice(0,n);r+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,Mo(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,r,n){return this._sendPacket("message",t,r,n),this}send(t,r,n){return this._sendPacket("message",t,r,n),this}_sendPacket(t,r,n,i){if(typeof r=="function"&&(i=r,r=void 0),typeof n=="function"&&(i=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const s={type:t,data:r,options:n};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),i&&this.once("flush",i),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},r=()=>{this.off("upgrade",r),this.off("upgradeError",r),t()},n=()=>{this.once("upgrade",r),this.once("upgradeError",r)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}_onError(t){if(Qr.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),wl&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=qs.indexOf(this._offlineEventListener);n!==-1&&qs.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,r),this.writeBuffer=[],this._prevBufferLen=0}}}Qr.protocol=Bh;class lg extends Qr{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t{n||(r.send([{type:"ping",data:"probe"}]),r.once("packet",y=>{if(!n)if(y.type==="pong"&&y.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",r),!r)return;Qr.priorWebsocketSuccess=r.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(w(),this.setTransport(r),r.send([{type:"upgrade"}]),this.emitReserved("upgrade",r),r=null,this.upgrading=!1,this.flush())})}else{const v=new Error("probe error");v.transport=r.name,this.emitReserved("upgradeError",v)}}))};function s(){n||(n=!0,w(),r.close(),r=null)}const o=y=>{const v=new Error("probe error: "+y);v.transport=r.name,s(),this.emitReserved("upgradeError",v)};function a(){o("transport closed")}function l(){o("socket closed")}function h(y){r&&y.name!==r.name&&s()}const w=()=>{r.removeListener("open",i),r.removeListener("error",o),r.removeListener("close",a),this.off("close",l),this.off("upgrading",h)};r.once("open",i),r.once("error",o),r.once("close",a),this.once("close",l),this.once("upgrading",h),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{n||r.open()},200):r.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const r=[];for(let n=0;nng[i]).filter(i=>!!i)),super(t,n)}};function cg(e,t="",r){let n=e;r=r||typeof location<"u"&&location,e==null&&(e=r.protocol+"//"+r.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=r.protocol+e:e=r.host+e),/^(https?|wss?):\/\//.test(e)||(typeof r<"u"?e=r.protocol+"//"+e:e="https://"+e),n=vl(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const s=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+s+":"+n.port+t,n.href=n.protocol+"://"+s+(r&&r.port===n.port?"":":"+n.port),n}const dg=typeof ArrayBuffer=="function",fg=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,qh=Object.prototype.toString,hg=typeof Blob=="function"||typeof Blob<"u"&&qh.call(Blob)==="[object BlobConstructor]",pg=typeof File=="function"||typeof File<"u"&&qh.call(File)==="[object FileConstructor]";function Tu(e){return dg&&(e instanceof ArrayBuffer||fg(e))||hg&&e instanceof Blob||pg&&e instanceof File}function Ks(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let r=0,n=e.length;r=0&&e.num{delete this.acks[t];for(let a=0;a{this.io.clearTimeoutFn(s),r.apply(this,a)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...r){return new Promise((n,i)=>{const s=(o,a)=>o?i(o):n(a);s.withError=!0,r.push(s),this.emit(t,...r)})}_addToQueue(t){let r;typeof t[t.length-1]=="function"&&(r=t.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((i,...s)=>n!==this._queue[0]?void 0:(i!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),r&&r(i)):(this._queue.shift(),r&&r(null,...s)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const r=this._queue[0];r.pending&&!t||(r.pending=!0,r.tryCount++,this.flags=r.flags,this.emit.apply(this,r.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:ke.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,r){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,r),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(n=>String(n.id)===t)){const n=this.acks[t];delete this.acks[t],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case ke.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case ke.EVENT:case ke.BINARY_EVENT:this.onevent(t);break;case ke.ACK:case ke.BINARY_ACK:this.onack(t);break;case ke.DISCONNECT:this.ondisconnect();break;case ke.CONNECT_ERROR:this.destroy();const n=new Error(t.data.message);n.data=t.data.data,this.emitReserved("connect_error",n);break}}onevent(t){const r=t.data||[];t.id!=null&&r.push(this.ack(t.id)),this.connected?this.emitEvent(r):this.receiveBuffer.push(Object.freeze(r))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const r=this._anyListeners.slice();for(const n of r)n.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const r=this;let n=!1;return function(...i){n||(n=!0,r.packet({type:ke.ACK,id:t,data:i}))}}onack(t){const r=this.acks[t.id];typeof r=="function"&&(delete this.acks[t.id],r.withError&&t.data.unshift(null),r.apply(this,t.data))}onconnect(t,r){this.id=t,this.recovered=r&&this._pid===r,this._pid=r,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:ke.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const r=this._anyListeners;for(let n=0;n0&&e.jitter<=1?e.jitter:0,this.attempts=0}fi.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+r:e-r}return Math.min(e,this.max)|0};fi.prototype.reset=function(){this.attempts=0};fi.prototype.setMin=function(e){this.ms=e};fi.prototype.setMax=function(e){this.max=e};fi.prototype.setJitter=function(e){this.jitter=e};class kl extends Ue{constructor(t,r){var n;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(r=t,t=void 0),r=r||{},r.path=r.path||"/socket.io",this.opts=r,Do(this,r),this.reconnection(r.reconnection!==!1),this.reconnectionAttempts(r.reconnectionAttempts||1/0),this.reconnectionDelay(r.reconnectionDelay||1e3),this.reconnectionDelayMax(r.reconnectionDelayMax||5e3),this.randomizationFactor((n=r.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new fi({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(r.timeout==null?2e4:r.timeout),this._readyState="closed",this.uri=t;const i=r.parser||_g;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=r.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var r;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(r=this.backoff)===null||r===void 0||r.setMin(t),this)}randomizationFactor(t){var r;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(r=this.backoff)===null||r===void 0||r.setJitter(t),this)}reconnectionDelayMax(t){var r;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(r=this.backoff)===null||r===void 0||r.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new ug(this.uri,this.opts);const r=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=$t(r,"open",function(){n.onopen(),t&&t()}),s=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),t?t(a):this.maybeReconnectOnOpen()},o=$t(r,"error",s);if(this._timeout!==!1){const a=this._timeout,l=this.setTimeoutFn(()=>{i(),s(new Error("timeout")),r.close()},a);this.opts.autoUnref&&l.unref(),this.subs.push(()=>{this.clearTimeoutFn(l)})}return this.subs.push(i),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push($t(t,"ping",this.onping.bind(this)),$t(t,"data",this.ondata.bind(this)),$t(t,"error",this.onerror.bind(this)),$t(t,"close",this.onclose.bind(this)),$t(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(r){this.onclose("parse error",r)}}ondecoded(t){Mo(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,r){let n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new Kh(this,t,r),this.nsps[t]=n),n}_destroy(t){const r=Object.keys(this.nsps);for(const n of r)if(this.nsps[n].active)return;this._close()}_packet(t){const r=this.encoder.encode(t);for(let n=0;nt()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,r){var n;this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,r),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const r=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(i=>{i?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",i)):t.onreconnect()}))},r);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const Si={};function Ys(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const r=cg(e,t.path||"/socket.io"),n=r.source,i=r.id,s=r.path,o=Si[i]&&s in Si[i].nsps,a=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let l;return a?l=new kl(n,t):(Si[i]||(Si[i]=new kl(n,t)),l=Si[i]),r.query&&!t.query&&(t.query=r.queryKey),l.socket(r.path,t)}Object.assign(Ys,{Manager:kl,Socket:Kh,io:Ys,connect:Ys});const Sg={},Yc=e=>{let t;const r=new Set,n=(w,y)=>{const v=typeof w=="function"?w(t):w;if(!Object.is(v,t)){const p=t;t=y??(typeof v!="object"||v===null)?v:Object.assign({},t,v),r.forEach(x=>x(t,p))}},i=()=>t,l={setState:n,getState:i,getInitialState:()=>h,subscribe:w=>(r.add(w),()=>r.delete(w)),destroy:()=>{(Sg?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),r.clear()}},h=t=e(n,i,l);return l},bg=e=>e?Yc(e):Yc;var Yh={exports:{}},Zh={},Xh={exports:{}},Qh={};/** + * @license React + * use-sync-external-store-shim.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var ai=G;function Cg(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Eg=typeof Object.is=="function"?Object.is:Cg,Ng=ai.useState,Rg=ai.useEffect,Tg=ai.useLayoutEffect,zg=ai.useDebugValue;function Ig(e,t){var r=t(),n=Ng({inst:{value:r,getSnapshot:t}}),i=n[0].inst,s=n[1];return Tg(function(){i.value=r,i.getSnapshot=t,va(i)&&s({inst:i})},[e,r,t]),Rg(function(){return va(i)&&s({inst:i}),e(function(){va(i)&&s({inst:i})})},[e]),zg(r),r}function va(e){var t=e.getSnapshot;e=e.value;try{var r=t();return!Eg(e,r)}catch{return!0}}function jg(e,t){return t()}var Lg=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?jg:Ig;Qh.useSyncExternalStore=ai.useSyncExternalStore!==void 0?ai.useSyncExternalStore:Lg;Xh.exports=Qh;var Og=Xh.exports;/** + * @license React + * use-sync-external-store-shim/with-selector.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Fo=G,Ag=Og;function Pg(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Mg=typeof Object.is=="function"?Object.is:Pg,Dg=Ag.useSyncExternalStore,Fg=Fo.useRef,Bg=Fo.useEffect,Ug=Fo.useMemo,$g=Fo.useDebugValue;Zh.useSyncExternalStoreWithSelector=function(e,t,r,n,i){var s=Fg(null);if(s.current===null){var o={hasValue:!1,value:null};s.current=o}else o=s.current;s=Ug(function(){function l(p){if(!h){if(h=!0,w=p,p=n(p),i!==void 0&&o.hasValue){var x=o.value;if(i(x,p))return y=x}return y=p}if(x=y,Mg(w,p))return x;var u=n(p);return i!==void 0&&i(x,u)?(w=p,x):(w=p,y=u)}var h=!1,w,y,v=r===void 0?null:r;return[function(){return l(t())},v===null?void 0:function(){return l(v())}]},[t,r,n,i]);var a=Dg(e,s[0],s[1]);return Bg(function(){o.hasValue=!0,o.value=a},[a]),$g(a),a};Yh.exports=Zh;var Wg=Yh.exports;const Vg=Il(Wg),Gh={},{useDebugValue:Hg}=ye,{useSyncExternalStoreWithSelector:qg}=Vg;let Zc=!1;const Kg=e=>e;function Yg(e,t=Kg,r){(Gh?"production":void 0)!=="production"&&r&&!Zc&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),Zc=!0);const n=qg(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,r);return Hg(n),n}const Xc=e=>{(Gh?"production":void 0)!=="production"&&typeof e!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const t=typeof e=="function"?bg(e):e,r=(n,i)=>Yg(t,n,i);return Object.assign(r,t),r},Bo=e=>e?Xc(e):Xc,yt=Bo(e=>({theme:"light",mobileView:"main",thumbnailHeight:200,isResizingPanels:!1,resizingSide:null,setTheme:t=>e({theme:t}),toggleTheme:()=>e(t=>({theme:t.theme==="light"?"dark":"light"})),setMobileView:t=>e({mobileView:t}),setThumbnailHeight:t=>e({thumbnailHeight:t}),setIsResizingPanels:t=>e({isResizingPanels:t}),setResizingSide:t=>e({resizingSide:t})})),rr=Bo((e,t)=>({libraries:[],currentLibraryId:null,setLibraries:r=>e({libraries:r}),setCurrentLibrary:r=>e({currentLibraryId:r}),addLibrary:r=>e(n=>({libraries:[...n.libraries,r]})),removeLibrary:r=>e(n=>({libraries:n.libraries.filter(i=>i.id!==r),currentLibraryId:n.currentLibraryId===r?null:n.currentLibraryId})),updateLibrary:(r,n)=>e(i=>({libraries:i.libraries.map(s=>s.id===r?{...s,...n}:s)})),getCurrentLibrary:()=>{const{libraries:r,currentLibraryId:n}=t();return r.find(i=>i.id===n)}})),_e=Bo((e,t)=>({images:[],selectedImage:null,selectedImages:[],totalImageCount:0,folders:[],selectedFolder:null,searchKeywords:"",filters:{formats:[],minSize:null,maxSize:null,startDate:null,endDate:null},imageLoadingState:{isLoading:!1,loadedCount:0,totalCount:0,hasMore:!1},setImages:r=>e({images:r}),appendImages:r=>e(n=>({images:[...n.images,...r]})),clearImages:()=>e({images:[]}),setSelectedImage:r=>e({selectedImage:r}),setSelectedImages:r=>e({selectedImages:r}),toggleImageSelection:r=>e(n=>({selectedImages:n.selectedImages.some(s=>s.path===r.path)?n.selectedImages.filter(s=>s.path!==r.path):[...n.selectedImages,r]})),clearSelection:()=>e({selectedImages:[],selectedImage:null}),setFolders:r=>e({folders:r}),setSelectedFolder:r=>e({selectedFolder:r}),setSearchKeywords:r=>e({searchKeywords:r}),setFilters:r=>e(n=>({filters:{...n.filters,...r}})),resetFilters:()=>e({searchKeywords:"",filters:{formats:[],minSize:null,maxSize:null,startDate:null,endDate:null}}),setTotalImageCount:r=>e({totalImageCount:r}),setImageLoadingState:r=>e(n=>({imageLoadingState:{...n.imageLoadingState,...r}}))})),cn=Bo((e,t)=>({scanProgress:null,scanStartTime:null,setScanProgress:r=>e(n=>r&&!n.scanStartTime&&r.current>0?{scanProgress:r,scanStartTime:Date.now()}:r?{scanProgress:r}:{scanProgress:null,scanStartTime:null}),clearScanProgress:()=>e({scanProgress:null,scanStartTime:null}),getEstimatedTimeLeft:()=>{const{scanProgress:r,scanStartTime:n}=t();if(!r||!n||r.current===0)return null;const i=Date.now()-n,s=r.current/i,o=r.total-r.current;return Math.ceil(o/s/1e3)},isScanning:()=>{const{scanProgress:r}=t();return r&&r.status!=="preparing"}})),Zg="/api";class wa extends Error{constructor(t,r,n){super(t),this.name="APIError",this.status=r,this.data=n}}async function Uo(e,t={}){var n;const r={headers:{"Content-Type":"application/json",...t.headers},...t};try{const i=await fetch(`${Zg}${e}`,r),s=await i.json();if(!i.ok)throw new wa(((n=s.error)==null?void 0:n.message)||s.error||"Request failed",i.status,s);return s.data!==void 0?s.data:s}catch(i){throw i instanceof wa?i:new wa(i.message||"Network error",0,null)}}function Xg(e,t={}){return Uo(e,{method:"GET",...t})}function Qg(e,t,r={}){return Uo(e,{method:"POST",body:JSON.stringify(t),...r})}function Gg(e,t,r={}){return Uo(e,{method:"PUT",body:JSON.stringify(t),...r})}function Jg(e,t={}){return Uo(e,{method:"DELETE",...t})}const Qe={get:Xg,post:Qg,put:Gg,delete:Jg};async function ey(){return Qe.get("/library")}async function ty(e,t){return Qe.post("/library",{name:e,path:t})}async function ry(e,t){return Qe.put(`/library/${e}`,t)}async function Jh(e){return Qe.delete(`/library/${e}`)}const ny=Jh;async function iy(e){return Qe.post(`/library/${e}/set-current`)}async function sy(e){return Qe.put("/library/preferences",e)}async function oy(e){return Qe.put("/library/theme",{theme:e})}const ay=Object.freeze(Object.defineProperty({__proto__:null,add:ty,deleteLibrary:ny,getAll:ey,remove:Jh,setCurrent:iy,update:ry,updatePreferences:sy,updateTheme:oy},Symbol.toStringTag,{value:"Module"}));async function ly(e,t={},r={}){const n=new URLSearchParams({libraryId:e,...t});return Qe.get(`/image?${n}`,r)}async function uy(e){return Qe.get(`/image/count?libraryId=${e}`)}async function cy(e){return Qe.get(`/image/stats?libraryId=${e}`)}async function dy(e){return Qe.get(`/image/folders?libraryId=${e}`)}async function fy(e){return Qe.get(`/image/cache-meta?libraryId=${e}`)}function hy(e,t){return`/api/image/thumbnail/${e}/${t}`}function py(e,t){return`/api/image/original/${e}/${t}`}async function my(e,t){return Qe.post(`/image/${e}/open-file`,{path:t})}const gy=Object.freeze(Object.defineProperty({__proto__:null,getCacheMeta:fy,getCount:uy,getFolders:dy,getOriginalUrl:py,getStats:cy,getThumbnailUrl:hy,openInExplorer:my,search:ly},Symbol.toStringTag,{value:"Module"}));async function yy(e,t=!1){return Qe.post("/scan/full",{libraryId:e,wait:t})}async function vy(e,t=!1){return Qe.post("/scan/sync",{libraryId:e,wait:t})}async function wy(e){return Qe.get(`/scan/status/${e}`)}async function xy(e){return Qe.post("/scan/fix-folders",{libraryId:e})}const _y=Object.freeze(Object.defineProperty({__proto__:null,fixFolders:xy,fullScan:yy,getStatus:wy,sync:vy},Symbol.toStringTag,{value:"Module"})),xr=ay,Le=gy,li=_y;class ky{constructor(){this.blobUrls=new Set,this.eventListeners=new Map,this.pendingLoads=new Set}registerBlobUrl(t){t&&t.startsWith("blob:")&&this.blobUrls.add(t)}revokeBlobUrl(t){if(t&&t.startsWith("blob:"))try{URL.revokeObjectURL(t),this.blobUrls.delete(t)}catch(r){console.warn("[DOMCleanup] Failed to revoke blob URL:",r)}}revokeAllBlobUrls(){let t=0;for(const r of this.blobUrls)try{URL.revokeObjectURL(r),t++}catch(n){console.warn("[DOMCleanup] Failed to revoke blob URL:",n)}this.blobUrls.clear(),t>0&&console.log(`[DOMCleanup] Revoked ${t} blob URLs`)}clearImageSources(t){if(!t)return;const r=t.querySelectorAll("img");let n=0;r.forEach(i=>{i.src&&(i.src.startsWith("blob:")&&this.revokeBlobUrl(i.src),i.src="",n++)}),n>0&&console.log(`[DOMCleanup] Cleared ${n} image sources`)}registerEventListener(t,r,n){this.eventListeners.has(t)||this.eventListeners.set(t,[]),this.eventListeners.get(t).push({event:r,handler:n})}removeEventListeners(t){const r=this.eventListeners.get(t);r&&(r.forEach(({event:n,handler:i})=>{try{t.removeEventListener(n,i)}catch(s){console.warn("[DOMCleanup] Failed to remove event listener:",s)}}),this.eventListeners.delete(t))}removeAllEventListeners(){let t=0;for(const[r,n]of this.eventListeners.entries())n.forEach(({event:i,handler:s})=>{try{r.removeEventListener(i,s),t++}catch(o){console.warn("[DOMCleanup] Failed to remove event listener:",o)}});this.eventListeners.clear(),t>0&&console.log(`[DOMCleanup] Removed ${t} event listeners`)}registerPendingLoad(t){this.pendingLoads.add(t)}cancelPendingLoad(t){if(this.pendingLoads.has(t))try{t.abort(),this.pendingLoads.delete(t)}catch(r){console.warn("[DOMCleanup] Failed to cancel pending load:",r)}}cancelPendingLoads(){let t=0;for(const r of this.pendingLoads)try{r.abort(),t++}catch(n){console.warn("[DOMCleanup] Failed to cancel pending load:",n)}this.pendingLoads.clear(),t>0&&console.log(`[DOMCleanup] Cancelled ${t} pending loads`)}suggestGarbageCollection(){try{new Array(1e3).fill(new Array(1e3).fill(0)).length>0}catch{}window.requestIdleCallback&&window.requestIdleCallback(()=>{})}cleanup(){console.log("[DOMCleanup] Performing complete cleanup..."),this.revokeAllBlobUrls(),this.removeAllEventListeners(),this.cancelPendingLoads(),this.suggestGarbageCollection(),console.log("[DOMCleanup] Cleanup complete")}getStatus(){return{blobUrls:this.blobUrls.size,eventListeners:this.eventListeners.size,pendingLoads:this.pendingLoads.size}}}const Sl=new ky;/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */var Sy={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const by=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().trim(),Re=(e,t)=>{const r=G.forwardRef(({color:n="currentColor",size:i=24,strokeWidth:s=2,absoluteStrokeWidth:o,className:a="",children:l,...h},w)=>G.createElement("svg",{ref:w,...Sy,width:i,height:i,stroke:n,strokeWidth:o?Number(s)*24/Number(i):s,className:["lucide",`lucide-${by(e)}`,a].join(" "),...h},[...t.map(([y,v])=>G.createElement(y,v)),...Array.isArray(l)?l:[l]]));return r.displayName=`${e}`,r};/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Cy=Re("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ey=Re("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Qc=Re("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ny=Re("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ry=Re("ChevronsDown",[["path",{d:"m7 6 5 5 5-5",key:"1lc07p"}],["path",{d:"m7 13 5 5 5-5",key:"1d48rs"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ty=Re("ChevronsRight",[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const zy=Re("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Iy=Re("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const jy=Re("ExternalLink",[["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}],["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["line",{x1:"10",x2:"21",y1:"14",y2:"3",key:"18c3s4"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ly=Re("FileText",[["path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z",key:"1nnpy2"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}],["line",{x1:"16",x2:"8",y1:"13",y2:"13",key:"14keom"}],["line",{x1:"16",x2:"8",y1:"17",y2:"17",key:"17nazh"}],["line",{x1:"10",x2:"8",y1:"9",y2:"9",key:"1a5vjj"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Oy=Re("File",[["path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z",key:"1nnpy2"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Gc=Re("Filter",[["polygon",{points:"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3",key:"1yg77f"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ay=Re("FolderDown",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"m15 13-3 3-3-3",key:"6j2sf0"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Di=Re("Folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Py=Re("HardDrive",[["line",{x1:"22",x2:"2",y1:"12",y2:"12",key:"1y58io"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}],["line",{x1:"6",x2:"6.01",y1:"16",y2:"16",key:"sgf278"}],["line",{x1:"10",x2:"10.01",y1:"16",y2:"16",key:"1l4acy"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const My=Re("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Jc=Re("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Dy=Re("Music",[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Fy=Re("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",key:"1xcu5"}],["circle",{cx:"17.5",cy:"10.5",r:".5",key:"736e4u"}],["circle",{cx:"8.5",cy:"7.5",r:".5",key:"clrty"}],["circle",{cx:"6.5",cy:"12.5",r:".5",key:"1s4xz9"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const By=Re("Play",[["polygon",{points:"5 3 19 12 5 21 5 3",key:"191637"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ed=Re("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const bl=Re("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const td=Re("Sliders",[["line",{x1:"4",x2:"4",y1:"21",y2:"14",key:"1p332r"}],["line",{x1:"4",x2:"4",y1:"10",y2:"3",key:"gb41h5"}],["line",{x1:"12",x2:"12",y1:"21",y2:"12",key:"hf2csr"}],["line",{x1:"12",x2:"12",y1:"8",y2:"3",key:"1kfi7u"}],["line",{x1:"20",x2:"20",y1:"21",y2:"16",key:"1lhrwl"}],["line",{x1:"20",x2:"20",y1:"12",y2:"3",key:"16vvfq"}],["line",{x1:"2",x2:"6",y1:"14",y2:"14",key:"1uebub"}],["line",{x1:"10",x2:"14",y1:"8",y2:"8",key:"1yglbp"}],["line",{x1:"18",x2:"22",y1:"16",y2:"16",key:"1jxqpz"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const rd=Re("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Uy=Re("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/** + * @license lucide-react v0.300.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ep=Re("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),rs={LIBRARY:"library",FOLDER:"folder",IMAGES:"images"};let nd=0;const $y=()=>(nd+=1,`req_${Date.now()}_${nd}`);class Wy{constructor(){this.activeRequests=new Map,this.requestContexts=new Map}createRequest(t){const r=$y(),n=new AbortController,i={id:r,type:t,createdAt:Date.now(),abortController:n,signal:n.signal,status:"pending",isActive:!0,cancel:()=>{if(i.isActive){i.isActive=!1,i.status="cancelled",n.abort(),this.requestContexts.delete(r);const s=this.activeRequests.get(t);s&&s.delete(r)}}};return this.requestContexts.set(r,i),this.activeRequests.has(t)||this.activeRequests.set(t,new Map),this.activeRequests.get(t).set(r,i),i}cancelAll(t){const r=this.activeRequests.get(t);if(r){for(const n of r.values())n.cancel();r.clear()}}cancelAllRequests(){for(const t of Object.values(rs))this.cancelAll(t)}isValid(t){const r=this.requestContexts.get(t);return r?r.isActive:!1}complete(t){const r=this.requestContexts.get(t);if(r&&r.isActive){r.status="completed",r.isActive=!1,this.requestContexts.delete(t);const n=this.activeRequests.get(r.type);n&&n.delete(t)}}error(t){const r=this.requestContexts.get(t);if(r&&r.isActive){r.status="error",r.isActive=!1,this.requestContexts.delete(t);const n=this.activeRequests.get(r.type);n&&n.delete(t)}}getActiveCount(t){const r=this.activeRequests.get(t);return r?r.size:0}hasActiveRequests(t){return this.getActiveCount(t)>0}}const jt=new Wy;function Cl(){jt.cancelAll(rs.IMAGES)}function Vy(e){e&&setTimeout(()=>{},300)}const Hy=async e=>{try{const t=await li.getStatus(e);return t.data||t}catch{return null}};function id(){const{libraries:e,currentLibraryId:t,setCurrentLibrary:r,addLibrary:n,removeLibrary:i}=rr(),{folders:s,selectedFolder:o,totalImageCount:a,setSelectedFolder:l}=_e(),{isScanning:h}=cn(),[w,y]=G.useState(!1),[v,p]=G.useState(""),[x,u]=G.useState(""),[_,c]=G.useState(""),[d,g]=G.useState(""),[S,b]=G.useState(new Set),[R,z]=G.useState(!1),[O,I]=G.useState(!1),P=G.useRef(null),re=B=>{g(B),P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{c(B)},300)};G.useEffect(()=>()=>{P.current&&clearTimeout(P.current)},[]);const T=async()=>{var B,N;if(h()){alert("扫描进行中,请稍后再试或暂停扫描");return}if(!v.trim()){alert("请输入素材库名称");return}if(!x.trim()){alert("请输入文件夹路径");return}z(!0);try{console.log("📝 添加素材库...");const V=await xr.add(v.trim(),x.trim()),j=V.id,W=V.hasExistingIndex;if(n({id:j,name:v.trim(),path:x.trim()}),p(""),u(""),y(!1),z(!1),console.log("🔄 切换到新素材库..."),await xr.setCurrent(j),r(j),l(null),_e.getState().setImages([]),_e.getState().setFolders([]),_e.getState().setSelectedImage(null),_e.getState().setTotalImageCount(0),cn.getState().setScanProgress({libraryId:j,current:0,total:0,percent:0,status:"preparing"}),W){console.log("检测到已有索引,先加载现有数据...");try{const[q,X]=await Promise.all([Le.getFolders(j),Le.getCount(j)]);_e.getState().setFolders(q.folders),_e.getState().setTotalImageCount(X.count),console.log("✅ 已加载现有数据")}catch(q){console.warn("⚠️ 加载现有数据失败:",q)}}console.log("🔍 开始异步扫描..."),W?(console.log("执行增量同步,检测变化..."),li.sync(j,!1)):(console.log("首次添加,执行全量扫描..."),li.fullScan(j,!1)),console.log("✅ 扫描已启动,请等待进度显示...")}catch(V){console.error("❌ Error adding library:",V);let j=V.message||"未知错误";(N=(B=V.response)==null?void 0:B.data)!=null&&N.message&&(j=V.response.data.message),j.includes("无法访问")||j.includes("权限")||j.includes("数据共享")?alert(`⚠️ 文件夹权限不足 + +`+j+` + +操作步骤: +1. 应用中心找到 FlyPic 应用 +2. 点击 应用设置 +3. 将该文件夹添加到 FlyPic 应用的读写权限`):alert("添加素材库失败: "+j),cn.getState().setScanProgress(null),z(!1)}},H=async B=>{if(B!==t){if(h()){alert("扫描进行中,请稍后再试或暂停扫描");return}I(!0);try{Cl(),jt.cancelAllRequests(),cn.getState().setScanProgress(null),_e.getState().setSelectedImage(null),_e.getState().setImages([]),_e.getState().setFolders([]),_e.getState().setImageLoadingState({isLoading:!1,loadedCount:0,totalCount:0}),l(null),await xr.setCurrent(B);const[N,V]=await Promise.all([Le.getFolders(B),Le.getCount(B)]);_e.getState().setFolders(N.folders),_e.getState().setTotalImageCount(V.count),r(B),Hy(B).then(j=>{j&&j.status==="scanning"&&cn.getState().setScanProgress(j.progress)}).catch(()=>{})}catch(N){console.error("Error setting current library:",N),alert("切换素材库失败: "+N.message),_e.getState().setImageLoadingState({isLoading:!1})}finally{I(!1)}}},m=async()=>{if(!t)return;if(h()){alert("扫描进行中,请稍后再试或暂停扫描");return}const B=e.find(V=>V.id===t);if(!(!B||!confirm(`确定要删除素材库"${B.name}"吗? + +路径: ${B.path} + +⚠️ 注意: +• 将删除索引数据并释放数据库连接 +• 不会删除原始图片文件 +• .flypic 文件夹将保留,您可以手动删除`)))try{await xr.remove(t),i(t),_e.getState().setImages([]),_e.getState().setFolders([]),_e.getState().setSelectedImage(null),_e.getState().setSelectedFolder(null);const V=e.filter(j=>j.id!==t);if(V.length>0){const j=V[0];await xr.setCurrent(j.id),r(j.id)}console.log(`✅ 素材库已删除: ${B.name}`),console.log(`数据库连接已释放,可手动删除: ${B.path}\\.flypic`)}catch(V){console.error("Error deleting library:",V),alert("删除素材库失败: "+V.message)}},K=B=>{const N=new Set(S);N.has(B)?N.delete(B):N.add(B),b(N)},oe=B=>{const N=[],V=j=>{j.forEach(W=>{W.children&&W.children.length>0&&(N.push(W.path),V(W.children))})};return V(B),N},Q=()=>{const B=oe(J.length>0?J:s);b(new Set(B))},Y=()=>{b(new Set)},$=()=>{const B=oe(J.length>0?J:s);return B.length>0&&B.every(N=>S.has(N))},J=G.useMemo(()=>{if(!_)return s;const B=_.trim().toLowerCase().split(/\s+/).filter(W=>W.length>0);if(B.length===0)return s;const N=[],V=W=>W.reduce((q,X)=>{const ne=X.name.toLowerCase(),ce=X.path.toLowerCase(),de=B.every(D=>ne.includes(D)),f=B.every(D=>ce.includes(D));let F=[];return X.children&&X.children.length>0&&(F=V(X.children)),(de||f||F.length>0)&&(q.push({...X,children:F}),F.length>0&&N.push(X.path)),q},[]),j=V(s);return N.length>0&&setTimeout(()=>{b(W=>{const q=new Set(W);return N.forEach(X=>q.add(X)),q})},0),j},[s,_]),M=(B,N)=>{B.stopPropagation(),K(N)},A=B=>{const N=B.children&&B.children.length>0;o!==B.path?(Cl(),l(B.path)):N&&K(B.path)},le=(B,N=0)=>B.map(V=>{const j=S.has(V.path),W=V.children&&V.children.length>0,q=o===V.path;return k.jsxs("div",{children:[k.jsxs("div",{className:`flex items-center px-3 py-2 cursor-pointer rounded-md transition-colors ${q?"bg-blue-50 dark:bg-blue-900":"hover:bg-gray-100 dark:hover:bg-gray-700"}`,style:{paddingLeft:`${N*16+12}px`},onClick:()=>A(V),children:[W?k.jsx("div",{className:"flex items-center justify-center w-5 h-5 mr-1 cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 rounded",onClick:X=>M(X,V.path),children:j?k.jsx(Qc,{className:"w-4 h-4 text-gray-500"}):k.jsx(Ny,{className:"w-4 h-4 text-gray-500"})}):k.jsx("div",{className:"w-5 mr-1"}),k.jsx(Di,{className:"w-4 h-4 mr-2 text-gray-500 flex-shrink-0"}),k.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300 truncate flex-1",children:V.name}),k.jsx("span",{className:"text-xs text-gray-400 ml-2 flex-shrink-0",children:V.imageCount})]}),W&&j&&le(V.children,N+1)]},V.path)});return k.jsxs("div",{className:"w-full h-full border-r border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 flex flex-col",children:[k.jsxs("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700",children:[k.jsx("div",{className:"flex items-center justify-between mb-3",children:k.jsx("h2",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300",children:"素材库"})}),k.jsxs("div",{className:"flex gap-2",children:[k.jsxs("div",{className:"relative flex-1",children:[k.jsxs("select",{value:t||"",onChange:B=>{const N=B.target.value;if(N==="__add__"){if(h()){alert("扫描进行中,请稍后再试或暂停扫描");return}y(!0)}else N&&H(N)},disabled:O||h(),className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 appearance-none cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",style:{paddingRight:"2rem"},children:[e.length===0&&k.jsx("option",{value:"",children:"暂无素材库"}),e.map(B=>k.jsx("option",{value:B.id,children:B.name},B.id)),k.jsx("option",{value:"__add__",style:{borderTop:"1px solid #ccc"},children:"+ 添加新素材库"})]}),k.jsx(Qc,{className:"absolute right-2 top-2.5 w-4 h-4 text-gray-400 pointer-events-none"})]}),t&&e.length>0&&k.jsx("button",{onClick:m,disabled:h(),className:"px-3 py-2 border border-red-300 dark:border-red-600 rounded-lg hover:bg-red-50 dark:hover:bg-red-900 text-red-600 dark:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:h()?"扫描进行中,无法删除":"删除当前素材库",children:k.jsx(Uy,{className:"w-4 h-4"})})]}),w&&k.jsxs("div",{className:"mt-3 p-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-700",children:[k.jsxs("div",{className:"flex items-center justify-between mb-2",children:[k.jsx("h3",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"添加素材库"}),k.jsx("button",{onClick:()=>y(!1),className:"p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-600",children:k.jsx(ep,{className:"w-4 h-4 text-gray-500"})})]}),k.jsxs("div",{className:"space-y-2",children:[k.jsx("input",{type:"text",placeholder:"素材库名称",value:v,onChange:B=>p(B.target.value),onKeyDown:B=>B.key==="Enter"&&T(),autoFocus:!0,className:"w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"}),k.jsx("input",{type:"text",placeholder:"文件夹路径(例如:C:\\Users\\Pictures)",value:x,onChange:B=>u(B.target.value),onKeyDown:B=>B.key==="Enter"&&T(),className:"w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"}),k.jsxs("div",{className:"flex gap-2",children:[k.jsx("button",{onClick:()=>y(!1),className:"flex-1 px-3 py-1.5 border border-gray-300 dark:border-gray-600 rounded text-sm hover:bg-gray-100 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300",children:"取消"}),k.jsx("button",{onClick:T,disabled:R,className:"flex-1 px-3 py-1.5 bg-blue-500 text-white rounded text-sm hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed",children:R?"添加中...":"添加"})]})]})]})]}),k.jsxs("div",{className:"flex-1 overflow-y-auto p-4",children:[k.jsx("div",{className:"mb-3 space-y-2",children:k.jsxs("div",{className:"flex gap-2",children:[k.jsxs("div",{className:"relative flex-1",children:[k.jsx(bl,{className:"absolute left-2 top-2 w-4 h-4 text-gray-400"}),k.jsx("input",{type:"text",placeholder:"搜索文件夹(支持多关键词)...",value:d,onChange:B=>re(B.target.value),className:"w-full pl-8 pr-3 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"})]}),k.jsx("button",{onClick:$()?Y:Q,className:"px-2 py-1.5 border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-100 dark:hover:bg-gray-600 text-gray-600 dark:text-gray-400 transition-colors",title:$()?"折叠全部":"展开全部",children:$()?k.jsx(Ty,{className:"w-4 h-4"}):k.jsx(Ry,{className:"w-4 h-4"})})]})}),k.jsxs("div",{className:"space-y-1",children:[k.jsxs("div",{className:`flex items-center px-3 py-2 cursor-pointer rounded-md transition-colors ${o===null?"bg-blue-50 dark:bg-blue-900":"hover:bg-gray-100 dark:hover:bg-gray-700"}`,onClick:()=>l(null),children:[k.jsx("div",{className:"w-5 mr-1"}),k.jsx(Di,{className:"w-4 h-4 mr-2 text-blue-500 flex-shrink-0"}),k.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300 font-medium flex-1",children:"全部图片"}),k.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 ml-2",children:a})]}),(J.length>0||s.length>0)&&k.jsx("div",{className:"h-px bg-gray-200 dark:bg-gray-700 my-2"}),J.length>0?le(J):_?k.jsx("div",{className:"text-center py-8 text-gray-400 dark:text-gray-500 text-sm",children:"未找到匹配的文件夹"}):s.length===0?k.jsx("div",{className:"text-center py-8 text-gray-400 dark:text-gray-500 text-sm",children:"暂无文件夹"}):null]})]})]})}class qy{constructor(t={}){this.maxSize=t.maxSize||20,this.cache=new Map,this.accessOrder=[],this.stats={hitCount:0,missCount:0,evictionCount:0,totalSets:0,totalGets:0}}get(t){this.stats.totalGets++;const r=this.cache.get(t);return r?(this.stats.hitCount++,this._updateAccessOrder(t),r.accessCount=(r.accessCount||0)+1,r):(this.stats.missCount++,null)}set(t,r){this.stats.totalSets++,!this.cache.has(t)&&this.cache.size>=this.maxSize&&this.evictLRU();let n=null;r.blob&&(n=URL.createObjectURL(r.blob)),this.cache.set(t,{data:r,blobUrl:n,timestamp:Date.now(),accessCount:1}),this._updateAccessOrder(t)}remove(t){const r=this.cache.get(t);if(r){r.blobUrl&&URL.revokeObjectURL(r.blobUrl),this.cache.delete(t);const n=this.accessOrder.indexOf(t);n>-1&&this.accessOrder.splice(n,1)}}clear(){for(const[t,r]of this.cache.entries())r.blobUrl&&URL.revokeObjectURL(r.blobUrl);this.cache.clear(),this.accessOrder=[]}evictLRU(){if(this.accessOrder.length===0)return;const t=this.accessOrder[0];this.remove(t),this.stats.evictionCount++}size(){return this.cache.size}getStats(){const t=this.stats.totalGets>0?(this.stats.hitCount/this.stats.totalGets*100).toFixed(2):0;return{size:this.cache.size,maxSize:this.maxSize,hitCount:this.stats.hitCount,missCount:this.stats.missCount,evictionCount:this.stats.evictionCount,totalSets:this.stats.totalSets,totalGets:this.stats.totalGets,hitRate:parseFloat(t)}}_updateAccessOrder(t){const r=this.accessOrder.indexOf(t);r>-1&&this.accessOrder.splice(r,1),this.accessOrder.push(t)}has(t){return this.cache.has(t)}keys(){return Array.from(this.cache.keys())}logStats(){this.getStats()}}const sd=new qy;function qe(){return qe=Object.assign?Object.assign.bind():function(e){for(var t=1;t"u"||/ServerSideRendering/.test(navigator&&navigator.userAgent)?G.useEffect:G.useLayoutEffect;function Ln(e,t,r){var n=G.useRef(t);n.current=t,G.useEffect(function(){function i(s){n.current(s)}return e&&window.addEventListener(e,i,r),function(){e&&window.removeEventListener(e,i)}},[e])}var Yy=["container"];function Zy(e){var t=e.container,r=t===void 0?document.body:t,n=$o(e,Yy);return Oh.createPortal(ye.createElement("div",qe({},n)),r)}function Xy(e){return ye.createElement("svg",qe({width:"44",height:"44",viewBox:"0 0 768 768"},e),ye.createElement("path",{d:"M607.5 205.5l-178.5 178.5 178.5 178.5-45 45-178.5-178.5-178.5 178.5-45-45 178.5-178.5-178.5-178.5 45-45 178.5 178.5 178.5-178.5z"}))}function Qy(e){return ye.createElement("svg",qe({width:"44",height:"44",viewBox:"0 0 768 768"},e),ye.createElement("path",{d:"M640.5 352.5v63h-390l178.5 180-45 45-256.5-256.5 256.5-256.5 45 45-178.5 180h390z"}))}function Gy(e){return ye.createElement("svg",qe({width:"44",height:"44",viewBox:"0 0 768 768"},e),ye.createElement("path",{d:"M384 127.5l256.5 256.5-256.5 256.5-45-45 178.5-180h-390v-63h390l-178.5-180z"}))}function Jy(){return G.useEffect(function(){var e=document.body.style,t=e.overflow;return e.overflow="hidden",function(){e.overflow=t}},[]),null}function ad(e){var t=e.touches[0],r=t.clientX,n=t.clientY;if(e.touches.length>=2){var i=e.touches[1],s=i.clientX,o=i.clientY;return[(r+s)/2,(n+o)/2,Math.sqrt(Math.pow(s-r,2)+Math.pow(o-n,2))]}return[r,n,0]}var Dr=function(e,t,r,n){var i,s=r*t,o=(s-n)/2,a=e;return s<=n?(i=1,a=0):e>0&&o-e<=0?(i=2,a=o):e<0&&o+e<=0&&(i=3,a=-o),[i,a]};function xa(e,t,r,n,i,s,o,a,l,h){o===void 0&&(o=innerWidth/2),a===void 0&&(a=innerHeight/2),l===void 0&&(l=0),h===void 0&&(h=0);var w=Dr(e,s,r,innerWidth)[0],y=Dr(t,s,n,innerHeight),v=innerWidth/2,p=innerHeight/2;return{x:o-s/i*(o-(v+e))-v+(n/r>=3&&r*s===innerWidth?0:w?l/2:l),y:a-s/i*(a-(p+t))-p+(y[0]?h/2:h),lastCX:o,lastCY:a}}function Rl(e,t,r){var n=e%180!=0;return n?[r,t,n]:[t,r,n]}function _a(e,t,r){var n=Rl(r,innerWidth,innerHeight),i=n[0],s=n[1],o=0,a=i,l=s,h=e/t*s,w=t/e*i;return e=s?a=h:e>=i&&ti/s?l=w:t/e>=3&&!n[2]?o=((l=w)-s)/2:a=h,{width:a,height:l,x:0,y:o,pause:!0}}function zs(e,t){var r=t.leading,n=r!==void 0&&r,i=t.maxWait,s=t.wait,o=s===void 0?i||0:s,a=G.useRef(e);a.current=e;var l=G.useRef(0),h=G.useRef(),w=function(){return h.current&&clearTimeout(h.current)},y=G.useCallback(function(){var v=[].slice.call(arguments),p=Date.now();function x(){l.current=p,w(),a.current.apply(null,v)}var u=l.current,_=p-u;if(u===0&&(n&&x(),l.current=p),i!==void 0){if(_>i)return void x()}else _=1&&s&&s())};w()}function w(){l=requestAnimationFrame(h)}}var tv={T:0,L:0,W:0,H:0,FIT:void 0},tp=function(){var e=G.useRef(!1);return G.useEffect(function(){return e.current=!0,function(){e.current=!1}},[]),e},rv=["className"];function nv(e){var t=e.className,r=t===void 0?"":t,n=$o(e,rv);return ye.createElement("div",qe({className:"PhotoView__Spinner "+r},n),ye.createElement("svg",{viewBox:"0 0 32 32",width:"36",height:"36",fill:"white"},ye.createElement("path",{opacity:".25",d:"M16 0 A16 16 0 0 0 16 32 A16 16 0 0 0 16 0 M16 4 A12 12 0 0 1 16 28 A12 12 0 0 1 16 4"}),ye.createElement("path",{d:"M16 0 A16 16 0 0 1 32 16 L28 16 A12 12 0 0 0 16 4z"})))}var iv=["src","loaded","broken","className","onPhotoLoad","loadingElement","brokenElement"];function sv(e){var t=e.src,r=e.loaded,n=e.broken,i=e.className,s=e.onPhotoLoad,o=e.loadingElement,a=e.brokenElement,l=$o(e,iv),h=tp();return t&&!n?ye.createElement(ye.Fragment,null,ye.createElement("img",qe({className:"PhotoView__Photo"+(i?" "+i:""),src:t,onLoad:function(w){var y=w.target;h.current&&s({loaded:!0,naturalWidth:y.naturalWidth,naturalHeight:y.naturalHeight})},onError:function(){h.current&&s({broken:!0})},draggable:!1,alt:""},l)),!r&&(o?ye.createElement("span",{className:"PhotoView__icon"},o):ye.createElement(nv,{className:"PhotoView__icon"}))):a?ye.createElement("span",{className:"PhotoView__icon"},typeof a=="function"?a({src:t}):a):null}var ov={naturalWidth:void 0,naturalHeight:void 0,width:void 0,height:void 0,loaded:void 0,broken:!1,x:0,y:0,touched:!1,maskTouched:!1,rotate:0,scale:1,CX:0,CY:0,lastX:0,lastY:0,lastCX:0,lastCY:0,lastScale:1,touchTime:0,touchLength:0,pause:!0,stopRaf:!0,reach:void 0};function av(e){var t=e.item,r=t.src,n=t.render,i=t.width,s=i===void 0?0:i,o=t.height,a=o===void 0?0:o,l=t.originRef,h=e.visible,w=e.speed,y=e.easing,v=e.wrapClassName,p=e.className,x=e.style,u=e.loadingElement,_=e.brokenElement,c=e.onPhotoTap,d=e.onMaskTap,g=e.onReachMove,S=e.onReachUp,b=e.onPhotoResize,R=e.isActive,z=e.expose,O=xo(ov),I=O[0],P=O[1],re=G.useRef(0),T=tp(),H=I.naturalWidth,m=H===void 0?s:H,K=I.naturalHeight,oe=K===void 0?a:K,Q=I.width,Y=Q===void 0?s:Q,$=I.height,J=$===void 0?a:$,M=I.loaded,A=M===void 0?!r:M,le=I.broken,B=I.x,N=I.y,V=I.touched,j=I.stopRaf,W=I.maskTouched,q=I.rotate,X=I.scale,ne=I.CX,ce=I.CY,de=I.lastX,f=I.lastY,F=I.lastCX,D=I.lastCY,E=I.lastScale,C=I.touchTime,L=I.touchLength,Z=I.pause,ee=I.reach,U=Jn({onScale:function(te){return ie(Ts(te))},onRotate:function(te){q!==te&&(z({rotate:te}),P(qe({rotate:te},_a(m,oe,te))))}});function ie(te,pe,be){X!==te&&(z({scale:te}),P(qe({scale:te},xa(B,N,Y,J,X,te,pe,be),te<=1&&{x:0,y:0})))}var ue=zs(function(te,pe,be){if(be===void 0&&(be=0),(V||W)&&R){var lr=Rl(q,Y,J),ur=lr[0],Ct=lr[1];if(be===0&&re.current===0){var mt=Math.abs(te-ne)<=20,gt=Math.abs(pe-ce)<=20;if(mt&>)return void P({lastCX:te,lastCY:pe});re.current=mt?pe>ce?3:2:1}var Xt,nn=te-F,zr=pe-D;if(be===0){var sn=Dr(nn+de,X,ur,innerWidth)[0],Cn=Dr(zr+f,X,Ct,innerHeight);Xt=function(Ir,dr,fr,Qt){return dr&&Ir===1||Qt==="x"?"x":fr&&Ir>1||Qt==="y"?"y":void 0}(re.current,sn,Cn[0],ee),Xt!==void 0&&g(Xt,te,pe,X)}if(Xt==="x"||W)return void P({reach:"x"});var cr=Ts(X+(be-L)/100/2*X,m/Y,.2);z({scale:cr}),P(qe({touchLength:be,reach:Xt,scale:cr},xa(B,N,Y,J,X,cr,te,pe,nn,zr)))}},{maxWait:8});function ae(te){return!j&&!V&&(T.current&&P(qe({},te,{pause:h})),T.current)}var he,ve,me,Ve,Kt,nt,Yt,xe,ar=(Kt=function(te){return ae({x:te})},nt=function(te){return ae({y:te})},Yt=function(te){return T.current&&(z({scale:te}),P({scale:te})),!V&&T.current},xe=Jn({X:function(te){return Kt(te)},Y:function(te){return nt(te)},S:function(te){return Yt(te)}}),function(te,pe,be,lr,ur,Ct,mt,gt,Xt,nn,zr){var sn=Rl(nn,ur,Ct),Cn=sn[0],cr=sn[1],Ir=Dr(te,gt,Cn,innerWidth),dr=Ir[0],fr=Ir[1],Qt=Dr(pe,gt,cr,innerHeight),En=Qt[0],ls=Qt[1],Nn=Date.now()-zr;if(Nn>=200||gt!==mt||Math.abs(Xt-mt)>1){var jr=xa(te,pe,ur,Ct,mt,gt),hr=jr.x,on=jr.y,Et=dr?fr:hr!==te?hr:null,Rn=En?ls:on!==pe?on:null;return Et!==null&&dn(te,Et,xe.X),Rn!==null&&dn(pe,Rn,xe.Y),void(gt!==mt&&dn(mt,gt,xe.S))}var an=(te-be)/Nn,Lr=(pe-lr)/Nn,Or=Math.sqrt(Math.pow(an,2)+Math.pow(Lr,2)),pr=!1,mr=!1;(function(Mt,it){var st,Dt=Mt,gr=0,Nt=0,Tn=function(hi){st||(st=hi);var pi=hi-st,Iu=Math.sign(Mt),ju=-.001*Iu,Lu=Math.sign(-Dt)*Math.pow(Dt,2)*2e-4,ip=Dt*pi+(ju+Lu)*Math.pow(pi,2)/2;gr+=ip,st=hi,Iu*(Dt+=(ju+Lu)*pi)<=0?Rt():it(gr)?Gt():Rt()};function Gt(){Nt=requestAnimationFrame(Tn)}function Rt(){cancelAnimationFrame(Nt)}Gt()})(Or,function(Mt){var it=te+Mt*(an/Or),st=pe+Mt*(Lr/Or),Dt=Dr(it,mt,Cn,innerWidth),gr=Dt[0],Nt=Dt[1],Tn=Dr(st,mt,cr,innerHeight),Gt=Tn[0],Rt=Tn[1];if(gr&&!pr&&(pr=!0,dr?dn(it,Nt,xe.X):ld(Nt,it+(it-Nt),xe.X)),Gt&&!mr&&(mr=!0,En?dn(st,Rt,xe.Y):ld(Rt,st+(st-Rt),xe.Y)),pr&&mr)return!1;var hi=pr||xe.X(Nt),pi=mr||xe.Y(Rt);return hi&&pi})}),Zt=(he=c,ve=function(te,pe){ee||ie(X!==1?1:Math.max(2,m/Y),te,pe)},me=G.useRef(0),Ve=zs(function(){me.current=0,he.apply(void 0,[].slice.call(arguments))},{wait:300}),function(){var te=[].slice.call(arguments);me.current+=1,Ve.apply(void 0,te),me.current>=2&&(Ve.cancel(),me.current=0,ve.apply(void 0,te))});function Ge(te,pe){if(re.current=0,(V||W)&&R){P({touched:!1,maskTouched:!1,pause:!1,stopRaf:!1,reach:void 0});var be=Ts(X,m/Y);if(ar(B,N,de,f,Y,J,X,be,E,q,C),S(te,pe),ne===te&&ce===pe){if(V)return void Zt(te,pe);W&&d(te,pe)}}}function Tr(te,pe,be){be===void 0&&(be=0),P({touched:!0,CX:te,CY:pe,lastCX:te,lastCY:pe,lastX:B,lastY:N,lastScale:X,touchLength:be,touchTime:Date.now()})}function bn(te){P({maskTouched:!0,CX:te.clientX,CY:te.clientY,lastX:B,lastY:N})}Ln(yr?void 0:"mousemove",function(te){te.preventDefault(),ue(te.clientX,te.clientY)}),Ln(yr?void 0:"mouseup",function(te){Ge(te.clientX,te.clientY)}),Ln(yr?"touchmove":void 0,function(te){te.preventDefault();var pe=ad(te);ue.apply(void 0,pe)},{passive:!1}),Ln(yr?"touchend":void 0,function(te){var pe=te.changedTouches[0];Ge(pe.clientX,pe.clientY)},{passive:!1}),Ln("resize",zs(function(){A&&!V&&(P(_a(m,oe,q)),b())},{maxWait:8})),Nl(function(){R&&z(qe({scale:X,rotate:q},U))},[R]);var bt=function(te,pe,be,lr,ur,Ct,mt,gt,Xt,nn){var zr=function(hr,on,Et,Rn,an){var Lr=G.useRef(!1),Or=xo({lead:!0,scale:Et}),pr=Or[0],mr=pr.lead,Mt=pr.scale,it=Or[1],st=zs(function(Dt){try{return an(!0),it({lead:!1,scale:Dt}),Promise.resolve()}catch(gr){return Promise.reject(gr)}},{wait:Rn});return Nl(function(){Lr.current?(an(!1),it({lead:!0}),st(Et)):Lr.current=!0},[Et]),mr?[hr*Mt,on*Mt,Et/Mt]:[hr*Et,on*Et,1]}(Ct,mt,gt,Xt,nn),sn=zr[0],Cn=zr[1],cr=zr[2],Ir=function(hr,on,Et,Rn,an){var Lr=G.useState(tv),Or=Lr[0],pr=Lr[1],mr=G.useState(0),Mt=mr[0],it=mr[1],st=G.useRef(),Dt=Jn({OK:function(){return hr&&it(4)}});function gr(Nt){an(!1),it(Nt)}return G.useEffect(function(){if(st.current||(st.current=Date.now()),Et){if(function(Nt,Tn){var Gt=Nt&&Nt.current;if(Gt&&Gt.nodeType===1){var Rt=Gt.getBoundingClientRect();Tn({T:Rt.top,L:Rt.left,W:Rt.width,H:Rt.height,FIT:Gt.tagName==="IMG"?getComputedStyle(Gt).objectFit:void 0})}}(on,pr),hr)return Date.now()-st.current<250?(it(1),requestAnimationFrame(function(){it(2),requestAnimationFrame(function(){return gr(3)})}),void setTimeout(Dt.OK,Rn)):void it(4);gr(5)}},[hr,Et]),[Mt,Or]}(te,pe,be,Xt,nn),dr=Ir[0],fr=Ir[1],Qt=fr.W,En=fr.FIT,ls=innerWidth/2,Nn=innerHeight/2,jr=dr<3||dr>4;return[jr?Qt?fr.L:ls:lr+(ls-Ct*gt/2),jr?Qt?fr.T:Nn:ur+(Nn-mt*gt/2),sn,jr&&En?sn*(fr.H/Qt):Cn,dr===0?cr:jr?Qt/(Ct*gt)||.01:cr,jr?En?1:0:1,dr,En]}(h,l,A,B,N,Y,J,X,w,function(te){return P({pause:te})}),ge=bt[4],Ee=bt[6],Te="transform "+w+"ms "+y,ze={className:p,onMouseDown:yr?void 0:function(te){te.stopPropagation(),te.button===0&&Tr(te.clientX,te.clientY,0)},onTouchStart:yr?function(te){te.stopPropagation(),Tr.apply(void 0,ad(te))}:void 0,onWheel:function(te){if(!ee){var pe=Ts(X-te.deltaY/100/2,m/Y);P({stopRaf:!0}),ie(pe,te.clientX,te.clientY)}},style:{width:bt[2]+"px",height:bt[3]+"px",opacity:bt[5],objectFit:Ee===4?void 0:bt[7],transform:q?"rotate("+q+"deg)":void 0,transition:Ee>2?Te+", opacity "+w+"ms ease, height "+(Ee<4?w/2:Ee>4?w:0)+"ms "+y:void 0}};return ye.createElement("div",{className:"PhotoView__PhotoWrap"+(v?" "+v:""),style:x,onMouseDown:!yr&&R?bn:void 0,onTouchStart:yr&&R?function(te){return bn(te.touches[0])}:void 0},ye.createElement("div",{className:"PhotoView__PhotoBox",style:{transform:"matrix("+ge+", 0, 0, "+ge+", "+bt[0]+", "+bt[1]+")",transition:V||Z?void 0:Te,willChange:R?"transform":void 0}},r?ye.createElement(sv,qe({src:r,loaded:A,broken:le},ze,{onPhotoLoad:function(te){P(qe({},te,te.loaded&&_a(te.naturalWidth||0,te.naturalHeight||0,q)))},loadingElement:u,brokenElement:_})):n&&n({attrs:ze,scale:ge,rotate:q})))}var ud={x:0,touched:!1,pause:!1,lastCX:void 0,lastCY:void 0,bg:void 0,lastBg:void 0,overlay:!0,minimal:!0,scale:1,rotate:0};function lv(e){var t=e.loop,r=t===void 0?3:t,n=e.speed,i=e.easing,s=e.photoClosable,o=e.maskClosable,a=o===void 0||o,l=e.maskOpacity,h=l===void 0?1:l,w=e.pullClosable,y=w===void 0||w,v=e.bannerVisible,p=v===void 0||v,x=e.overlayRender,u=e.toolbarRender,_=e.className,c=e.maskClassName,d=e.photoClassName,g=e.photoWrapClassName,S=e.loadingElement,b=e.brokenElement,R=e.images,z=e.index,O=z===void 0?0:z,I=e.onIndexChange,P=e.visible,re=e.onClose,T=e.afterClose,H=e.portalContainer,m=xo(ud),K=m[0],oe=m[1],Q=G.useState(0),Y=Q[0],$=Q[1],J=K.x,M=K.touched,A=K.pause,le=K.lastCX,B=K.lastCY,N=K.bg,V=N===void 0?h:N,j=K.lastBg,W=K.overlay,q=K.minimal,X=K.scale,ne=K.rotate,ce=K.onScale,de=K.onRotate,f=e.hasOwnProperty("index"),F=f?O:Y,D=f?I:$,E=G.useRef(F),C=R.length,L=R[F],Z=typeof r=="boolean"?r:C>r,ee=function(ge,Ee){var Te=G.useReducer(function(be){return!be},!1)[1],ze=G.useRef(0),te=function(be){var lr=G.useRef(be);function ur(Ct){lr.current=Ct}return G.useMemo(function(){(function(Ct){ge?(Ct(ge),ze.current=1):ze.current=2})(ur)},[be]),[lr.current,ur]}(ge),pe=te[1];return[te[0],ze.current,function(){Te(),ze.current===2&&(pe(!1),Ee&&Ee()),ze.current=0}]}(P,T),U=ee[0],ie=ee[1],ue=ee[2];Nl(function(){if(U)return oe({pause:!0,x:F*-(innerWidth+In)}),void(E.current=F);oe(ud)},[U]);var ae=Jn({close:function(ge){de&&de(0),oe({overlay:!0,lastBg:V}),re(ge)},changeIndex:function(ge,Ee){Ee===void 0&&(Ee=!1);var Te=Z?E.current+(ge-F):ge,ze=C-1,te=El(Te,0,ze),pe=Z?Te:te,be=innerWidth+In;oe({touched:!1,lastCX:void 0,lastCY:void 0,x:-be*pe,pause:Ee}),E.current=pe,D&&D(Z?ge<0?ze:ge>ze?0:ge:te)}}),he=ae.close,ve=ae.changeIndex;function me(ge){return ge?he():oe({overlay:!W})}function Ve(){oe({x:-(innerWidth+In)*F,lastCX:void 0,lastCY:void 0,pause:!0}),E.current=F}function Kt(ge,Ee,Te,ze){ge==="x"?function(te){if(le!==void 0){var pe=te-le,be=pe;!Z&&(F===0&&pe>0||F===C-1&&pe<0)&&(be=pe/2),oe({touched:!0,lastCX:le,x:-(innerWidth+In)*E.current+be,pause:!1})}else oe({touched:!0,lastCX:te,x:J,pause:!1})}(Ee):ge==="y"&&function(te,pe){if(B!==void 0){var be=h===null?null:El(h,.01,h-Math.abs(te-B)/100/4);oe({touched:!0,lastCY:B,bg:pe===1?be:h,minimal:pe===1})}else oe({touched:!0,lastCY:te,bg:V,minimal:!0})}(Te,ze)}function nt(ge,Ee){var Te=ge-(le??ge),ze=Ee-(B??Ee),te=!1;if(Te<-40)ve(F+1);else if(Te>40)ve(F-1);else{var pe=-(innerWidth+In)*E.current;Math.abs(ze)>100&&q&&y&&(te=!0,he()),oe({touched:!1,x:pe,lastCX:void 0,lastCY:void 0,bg:h,overlay:!!te||W})}}Ln("keydown",function(ge){if(P)switch(ge.key){case"ArrowLeft":ve(F-1,!0);break;case"ArrowRight":ve(F+1,!0);break;case"Escape":he()}});var Yt=function(ge,Ee,Te){return G.useMemo(function(){var ze=ge.length;return Te?ge.concat(ge).concat(ge).slice(ze+Ee-1,ze+Ee+2):ge.slice(Math.max(Ee-1,0),Math.min(Ee+2,ze+1))},[ge,Ee,Te])}(R,F,Z);if(!U)return null;var xe=W&&!ie,ar=P?V:j,Zt=ce&&de&&{images:R,index:F,visible:P,onClose:he,onIndexChange:ve,overlayVisible:xe,overlay:L&&L.overlay,scale:X,rotate:ne,onScale:ce,onRotate:de},Ge=n?n(ie):400,Tr=i?i(ie):od,bn=n?n(3):600,bt=i?i(3):od;return ye.createElement(Zy,{className:"PhotoView-Portal"+(xe?"":" PhotoView-Slider__clean")+(P?"":" PhotoView-Slider__willClose")+(_?" "+_:""),role:"dialog",onClick:function(ge){return ge.stopPropagation()},container:H},P&&ye.createElement(Jy,null),ye.createElement("div",{className:"PhotoView-Slider__Backdrop"+(c?" "+c:"")+(ie===1?" PhotoView-Slider__fadeIn":ie===2?" PhotoView-Slider__fadeOut":""),style:{background:ar?"rgba(0, 0, 0, "+ar+")":void 0,transitionTimingFunction:Tr,transitionDuration:(M?0:Ge)+"ms",animationDuration:Ge+"ms"},onAnimationEnd:ue}),p&&ye.createElement("div",{className:"PhotoView-Slider__BannerWrap"},ye.createElement("div",{className:"PhotoView-Slider__Counter"},F+1," / ",C),ye.createElement("div",{className:"PhotoView-Slider__BannerRight"},u&&Zt&&u(Zt),ye.createElement(Xy,{className:"PhotoView-Slider__toolbarIcon",onClick:he}))),Yt.map(function(ge,Ee){var Te=Z||F!==0?E.current-1+Ee:F+Ee;return ye.createElement(av,{key:Z?ge.key+"/"+ge.src+"/"+Te:ge.key,item:ge,speed:Ge,easing:Tr,visible:P,onReachMove:Kt,onReachUp:nt,onPhotoTap:function(){return me(s)},onMaskTap:function(){return me(a)},wrapClassName:g,className:d,style:{left:(innerWidth+In)*Te+"px",transform:"translate3d("+J+"px, 0px, 0)",transition:M||A?void 0:"transform "+bn+"ms "+bt},loadingElement:S,brokenElement:b,onPhotoResize:Ve,isActive:E.current===Te,expose:oe})}),!yr&&p&&ye.createElement(ye.Fragment,null,(Z||F!==0)&&ye.createElement("div",{className:"PhotoView-Slider__ArrowLeft",onClick:function(){return ve(F-1,!0)}},ye.createElement(Qy,null)),(Z||F+1-1){var c=h.slice();return c.splice(_,1,u),void a({images:c})}a(function(d){return{images:d.images.concat(u)}})},remove:function(u){a(function(_){var c=_.images.filter(function(d){return d.key!==u});return{images:c,index:Math.min(c.length-1,y)}})},show:function(u){var _=h.findIndex(function(c){return c.key===u});a({visible:!0,index:_}),n&&n(!0,_,o)}}),p=Jn({close:function(){a({visible:!1}),n&&n(!1,y,o)},changeIndex:function(u){a({index:u}),r&&r(u,o)}}),x=G.useMemo(function(){return qe({},o,v)},[o,v]);return ye.createElement(Ky.Provider,{value:x},t,ye.createElement(lv,qe({images:h,visible:w,index:y,onIndexChange:p.changeIndex,onClose:p.close},i)))}function Tl(){return Tl=Object.assign?Object.assign.bind():function(e){for(var t=1;t=t?e.call(null):i.id=requestAnimationFrame(n)}var i={id:requestAnimationFrame(n)};return i}var Sa=-1;function pd(e){if(e===void 0&&(e=!1),Sa===-1||e){var t=document.createElement("div"),r=t.style;r.width="50px",r.height="50px",r.overflow="scroll",document.body.appendChild(t),Sa=t.offsetWidth-t.clientWidth,document.body.removeChild(t)}return Sa}var jn=null;function md(e){if(e===void 0&&(e=!1),jn===null||e){var t=document.createElement("div"),r=t.style;r.width="50px",r.height="50px",r.overflow="scroll",r.direction="rtl";var n=document.createElement("div"),i=n.style;return i.width="100px",i.height="100px",t.appendChild(n),document.body.appendChild(t),t.scrollLeft>0?jn="positive-descending":(t.scrollLeft=1,t.scrollLeft===0?jn="negative":jn="positive-ascending"),document.body.removeChild(t),jn}return jn}var yv=150,vv=function(t,r){return t};function wv(e){var t,r=e.getItemOffset,n=e.getEstimatedTotalSize,i=e.getItemSize,s=e.getOffsetForIndexAndAlignment,o=e.getStartIndexForOffset,a=e.getStopIndexForStartIndex,l=e.initInstanceProps,h=e.shouldResetStyleCacheOnItemSizeChange,w=e.validateProps;return t=function(y){fv(v,y);function v(x){var u;return u=y.call(this,x)||this,u._instanceProps=l(u.props,cd(u)),u._outerRef=void 0,u._resetIsScrollingTimeoutId=null,u.state={instance:cd(u),isScrolling:!1,scrollDirection:"forward",scrollOffset:typeof u.props.initialScrollOffset=="number"?u.props.initialScrollOffset:0,scrollUpdateWasRequested:!1},u._callOnItemsRendered=void 0,u._callOnItemsRendered=ka(function(_,c,d,g){return u.props.onItemsRendered({overscanStartIndex:_,overscanStopIndex:c,visibleStartIndex:d,visibleStopIndex:g})}),u._callOnScroll=void 0,u._callOnScroll=ka(function(_,c,d){return u.props.onScroll({scrollDirection:_,scrollOffset:c,scrollUpdateWasRequested:d})}),u._getItemStyle=void 0,u._getItemStyle=function(_){var c=u.props,d=c.direction,g=c.itemSize,S=c.layout,b=u._getItemStyleCache(h&&g,h&&S,h&&d),R;if(b.hasOwnProperty(_))R=b[_];else{var z=r(u.props,_,u._instanceProps),O=i(u.props,_,u._instanceProps),I=d==="horizontal"||S==="horizontal",P=d==="rtl",re=I?z:0;b[_]=R={position:"absolute",left:P?void 0:re,right:P?re:void 0,top:I?0:z,height:I?"100%":O,width:I?O:"100%"}}return R},u._getItemStyleCache=void 0,u._getItemStyleCache=ka(function(_,c,d){return{}}),u._onScrollHorizontal=function(_){var c=_.currentTarget,d=c.clientWidth,g=c.scrollLeft,S=c.scrollWidth;u.setState(function(b){if(b.scrollOffset===g)return null;var R=u.props.direction,z=g;if(R==="rtl")switch(md()){case"negative":z=-g;break;case"positive-descending":z=S-d-g;break}return z=Math.max(0,Math.min(z,S-d)),{isScrolling:!0,scrollDirection:b.scrollOffsetR.clientWidth?pd():0:b=R.scrollHeight>R.clientHeight?pd():0}this.scrollTo(s(this.props,u,_,S,this._instanceProps,b))},p.componentDidMount=function(){var u=this.props,_=u.direction,c=u.initialScrollOffset,d=u.layout;if(typeof c=="number"&&this._outerRef!=null){var g=this._outerRef;_==="horizontal"||d==="horizontal"?g.scrollLeft=c:g.scrollTop=c}this._callPropsCallbacks()},p.componentDidUpdate=function(){var u=this.props,_=u.direction,c=u.layout,d=this.state,g=d.scrollOffset,S=d.scrollUpdateWasRequested;if(S&&this._outerRef!=null){var b=this._outerRef;if(_==="horizontal"||c==="horizontal")if(_==="rtl")switch(md()){case"negative":b.scrollLeft=-g;break;case"positive-ascending":b.scrollLeft=g;break;default:var R=b.clientWidth,z=b.scrollWidth;b.scrollLeft=z-R-g;break}else b.scrollLeft=g;else b.scrollTop=g}this._callPropsCallbacks()},p.componentWillUnmount=function(){this._resetIsScrollingTimeoutId!==null&&hd(this._resetIsScrollingTimeoutId)},p.render=function(){var u=this.props,_=u.children,c=u.className,d=u.direction,g=u.height,S=u.innerRef,b=u.innerElementType,R=u.innerTagName,z=u.itemCount,O=u.itemData,I=u.itemKey,P=I===void 0?vv:I,re=u.layout,T=u.outerElementType,H=u.outerTagName,m=u.style,K=u.useIsScrolling,oe=u.width,Q=this.state.isScrolling,Y=d==="horizontal"||re==="horizontal",$=Y?this._onScrollHorizontal:this._onScrollVertical,J=this._getRangeToRender(),M=J[0],A=J[1],le=[];if(z>0)for(var B=M;B<=A;B++)le.push(G.createElement(_,{data:O,key:P(B,O),index:B,isScrolling:K?Q:void 0,style:this._getItemStyle(B)}));var N=n(this.props,this._instanceProps);return G.createElement(T||H||"div",{className:c,onScroll:$,ref:this._outerRefSetter,style:Tl({position:"relative",height:g,width:oe,overflow:"auto",WebkitOverflowScrolling:"touch",willChange:"transform",direction:d},m)},G.createElement(b||R||"div",{children:le,ref:S,style:{height:Y?"100%":N,pointerEvents:Q?"none":void 0,width:Y?N:"100%"}}))},p._callPropsCallbacks=function(){if(typeof this.props.onItemsRendered=="function"){var u=this.props.itemCount;if(u>0){var _=this._getRangeToRender(),c=_[0],d=_[1],g=_[2],S=_[3];this._callOnItemsRendered(c,d,g,S)}}if(typeof this.props.onScroll=="function"){var b=this.state,R=b.scrollDirection,z=b.scrollOffset,O=b.scrollUpdateWasRequested;this._callOnScroll(R,z,O)}},p._getRangeToRender=function(){var u=this.props,_=u.itemCount,c=u.overscanCount,d=this.state,g=d.isScrolling,S=d.scrollDirection,b=d.scrollOffset;if(_===0)return[0,0,0,0];var R=o(this.props,b,this._instanceProps),z=a(this.props,R,b,this._instanceProps),O=!g||S==="backward"?Math.max(1,c):1,I=!g||S==="forward"?Math.max(1,c):1;return[Math.max(0,R-O),Math.max(0,Math.min(_-1,z+I)),R,z]},v}(G.PureComponent),t.defaultProps={direction:"ltr",itemData:void 0,layout:"vertical",overscanCount:2,useIsScrolling:!1},t}var xv=function(t,r){t.children,t.direction,t.height,t.layout,t.innerTagName,t.outerTagName,t.width,r.instance},_v=50,qn=function(t,r,n){var i=t,s=i.itemSize,o=n.itemMetadataMap,a=n.lastMeasuredIndex;if(r>a){var l=0;if(a>=0){var h=o[a];l=h.offset+h.size}for(var w=a+1;w<=r;w++){var y=s(w);o[w]={offset:l,size:y},l+=y}n.lastMeasuredIndex=r}return o[r]},kv=function(t,r,n){var i=r.itemMetadataMap,s=r.lastMeasuredIndex,o=s>0?i[s].offset:0;return o>=n?rp(t,r,s,0,n):Sv(t,r,Math.max(0,s),n)},rp=function(t,r,n,i,s){for(;i<=n;){var o=i+Math.floor((n-i)/2),a=qn(t,o,r).offset;if(a===s)return o;as&&(n=o-1)}return i>0?i-1:0},Sv=function(t,r,n,i){for(var s=t.itemCount,o=1;n=n&&(o=n-1),o>=0){var l=i[o];a=l.offset+l.size}var h=n-o-1,w=h*s;return a+w},bv=wv({getItemOffset:function(t,r,n){return qn(t,r,n).offset},getItemSize:function(t,r,n){return n.itemMetadataMap[r].size},getEstimatedTotalSize:gd,getOffsetForIndexAndAlignment:function(t,r,n,i,s,o){var a=t.direction,l=t.height,h=t.layout,w=t.width,y=a==="horizontal"||h==="horizontal",v=y?w:l,p=qn(t,r,s),x=gd(t,s),u=Math.max(0,Math.min(x-v,p.offset)),_=Math.max(0,p.offset-v+p.size+o);switch(n==="smart"&&(i>=_-v&&i<=u+v?n="auto":n="center"),n){case"start":return u;case"end":return _;case"center":return Math.round(_+(u-_)/2);case"auto":default:return i>=_&&i<=u?i:i<_?_:u}},getStartIndexForOffset:function(t,r,n){return kv(t,n,r)},getStopIndexForStartIndex:function(t,r,n,i){for(var s=t.direction,o=t.height,a=t.itemCount,l=t.layout,h=t.width,w=s==="horizontal"||l==="horizontal",y=w?h:o,v=qn(t,r,i),p=n+y,x=v.offset+v.size,u=r;u{try{await Le.openInExplorer(t,e.path)}catch(o){console.error("Failed to open file:",o)}};return k.jsxs("div",{className:"fixed inset-0 z-50 bg-black bg-opacity-90 flex items-center justify-center",children:[k.jsxs("div",{className:"absolute top-0 left-0 right-0 h-16 bg-black bg-opacity-50 flex items-center justify-between px-4 z-10",children:[k.jsx("div",{className:"text-white text-sm truncate max-w-md",children:e.filename}),k.jsxs("div",{className:"flex items-center gap-2",children:[k.jsx("button",{onClick:s,className:"p-2 text-white hover:bg-white hover:bg-opacity-20 rounded transition-colors",title:"在系统默认应用中打开",children:k.jsx(jy,{className:"w-5 h-5"})}),k.jsx("button",{onClick:r,className:"p-2 text-white hover:bg-white hover:bg-opacity-20 rounded transition-colors",children:k.jsx(ep,{className:"w-6 h-6"})})]})]}),k.jsxs("div",{className:"w-full h-full flex items-center justify-center p-20",children:[n==="video"&&k.jsx("video",{src:i,controls:!0,autoPlay:!0,className:"max-w-full max-h-full rounded shadow-2xl",onError:o=>{console.error("Video load error:",o),alert("视频加载失败,请尝试在系统默认应用中打开")},children:"您的浏览器不支持视频播放"}),n==="audio"&&k.jsxs("div",{className:"flex flex-col items-center justify-center",children:[k.jsx("div",{className:"text-white text-6xl mb-8",children:"🎵"}),k.jsx("audio",{src:i,controls:!0,autoPlay:!0,className:"w-96 rounded shadow-2xl",onError:o=>{console.error("Audio load error:",o),alert("音频加载失败,请尝试在系统默认应用中打开")},children:"您的浏览器不支持音频播放"}),k.jsx("p",{className:"text-white mt-4 text-sm opacity-70",children:e.filename})]}),n==="document"&&k.jsx("div",{className:"w-full h-full bg-white rounded shadow-2xl overflow-hidden",children:e.format==="pdf"?k.jsx("iframe",{src:i,className:"w-full h-full",title:e.filename}):k.jsx("iframe",{src:i,className:"w-full h-full",title:e.filename,sandbox:"allow-same-origin"})}),(n==="design"||n==="other"||!n)&&k.jsxs("div",{className:"text-center text-white",children:[k.jsx("p",{className:"mb-4",children:"此文件类型需要在专业软件中打开"}),k.jsx("button",{onClick:s,className:"px-6 py-3 bg-blue-500 hover:bg-blue-600 rounded-lg transition-colors",children:"在系统默认应用中打开"})]})]}),k.jsx("div",{className:"absolute inset-0 -z-10",onClick:r})]})}const Ev=100,Is={pageSize:100,preloadThreshold:300,overscanCount:4};function Nv(){const{currentLibraryId:e}=rr(),{images:t,selectedImage:r,setSelectedImage:n,selectedImages:i,setSelectedImages:s,toggleImageSelection:o,clearSelection:a,imageLoadingState:l,selectedFolder:h,searchKeywords:w,filters:y,appendImages:v,setImageLoadingState:p}=_e(),x=t,{thumbnailHeight:u,isResizingPanels:_}=yt(),c=G.useRef(null),d=G.useRef(null),[g,S]=G.useState(0),[b,R]=G.useState(0),[z,O]=G.useState(-1),[I,P]=G.useState(null),[re,T]=G.useState(null),H=G.useCallback(async()=>{var V;if(!e||!l.hasMore||l.isLoading)return;const N=jt.createRequest(rs.IMAGES);p({isLoading:!0});try{const j={offset:t.length,limit:Is.pageSize};h&&(j.folder=h),w&&(j.keywords=w),((V=y.formats)==null?void 0:V.length)>0&&(j.formats=y.formats.join(","));const W=await Le.search(e,j,{signal:N.signal});if(!jt.isValid(N.id))return;const{images:q,total:X,hasMore:ne}=W;jt.complete(N.id),v(q),p({isLoading:!1,loadedCount:t.length+q.length,totalCount:X,hasMore:ne||!1})}catch(j){if(j.name==="CanceledError"||j.name==="AbortError")return;console.error("Error loading more images:",j),jt.error(N.id),p({isLoading:!1})}},[e,l,t.length,h,w,y,v,p]);G.useEffect(()=>{let N=null,V=0;const j=10,W={current:0};let q=null;const X=(de,f)=>(Math.abs(de-W.current)<12||(W.current=de,q&&clearTimeout(q),q=setTimeout(()=>{S(de),R(f)},50)),!0),ne=()=>{if(c.current){const de=c.current.offsetWidth-32,f=c.current.offsetHeight;if(de>0)return X(de,f)}return!1},ce=()=>{ne()?c.current&&(N=new ResizeObserver(()=>{yt.getState().isResizingPanels||ne()}),N.observe(c.current)):V{N&&N.disconnect(),q&&clearTimeout(q)}},[]),G.useEffect(()=>{if(_||!c.current)return;const N=c.current.offsetWidth-32,V=c.current.offsetHeight;N>0&&(S(N),R(V),d.current&&d.current.resetAfterIndex(0))},[_]);const m=G.useMemo(()=>{if(!x.length||!g)return[];const N=16,V=u,j=[];let W=[],q=0;return x.forEach((X,ne)=>{const ce=X.width/X.height,de=V*ce;W.push({...X,originalWidth:de,aspectRatio:ce}),q+=de;const f=(W.length-1)*N,F=q+f,D=ne===x.length-1;let E=!1;if(D)E=!0;else if(F>=g*.95)E=!0;else{const C=x[ne+1];if(C){const L=C.width/C.height,Z=V*L;q+Z+W.length*N>g*1.2&&(E=!0)}}if(E){const C=(W.length-1)*N;let Z=(g-C)/q;D&&W.length<3&&(Z=Math.min(Z,1.2));const ee=V*Z;W=W.map(U=>({...U,calculatedWidth:U.originalWidth*Z,calculatedHeight:ee})),j.push(W),W=[],q=0}}),j},[x,u,g]),K=N=>{const V=N.thumbnailPath;if(!e||!V)return"";const j=V.replace(/\\/g,"/").split("/").pop();return Le.getThumbnailUrl(e,j)},oe=N=>e?Le.getOriginalUrl(e,N.path):"",Q=G.useMemo(()=>x.map(N=>({src:oe(N),key:N.id})),[x,e]),Y=x.length>Ev,$=G.useCallback(N=>{if(!m||!m[N]||m[N].length===0)return u+40;const V=m[N][0];return((V==null?void 0:V.calculatedHeight)||u)+28+32},[m,u]),J=G.useRef(0);G.useEffect(()=>{if(d.current&&Y){const N=J.current,V=m.length;if(V>N&&N>0){const j=Math.max(0,N-1);d.current.resetAfterIndex(j)}else V!==N&&d.current.resetAfterIndex(0);J.current=V}},[m,Y]);const M=G.useMemo(()=>!m||m.length===0?[]:m.flat(),[m]),A=G.useCallback((N,V,j)=>{if(V.ctrlKey||V.metaKey)V.preventDefault(),o(N),P(j);else if(V.shiftKey&&I!==null){V.preventDefault();const W=Math.min(I,j),q=Math.max(I,j),X=M.slice(W,q+1);s(X)}else a(),n(N),P(j)},[M,I,o,s,a,n]),le=(N,V)=>{const j=(r==null?void 0:r.id)===N.id,W=i.some(X=>X.id===N.id),q=j||W;return k.jsxs("div",{className:"flex-shrink-0",style:{width:`${N.calculatedWidth}px`},children:[k.jsxs("div",{className:"relative group cursor-pointer overflow-hidden rounded-lg transition-all hover:shadow-lg",style:{height:`${N.calculatedHeight}px`,backgroundColor:"#2a2a2a",border:q?"3px solid #3b82f6":"3px solid transparent"},onClick:X=>A(N,X,V),onDoubleClick:()=>{(N.fileType||"image")==="image"?O(V):T(N)},children:[k.jsx("img",{src:K(N)||'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="200" height="200"%3E%3Crect fill="%23f3f4f6" width="200" height="200"/%3E%3Ctext x="50%25" y="45%25" dominant-baseline="middle" text-anchor="middle" fill="%239ca3af" font-family="sans-serif" font-size="14"%3E需要同步%3C/text%3E%3Ctext x="50%25" y="60%25" dominant-baseline="middle" text-anchor="middle" fill="%23d1d5db" font-family="sans-serif" font-size="12"%3E点击同步按钮%3C/text%3E%3C/svg%3E',alt:N.filename,className:"w-full h-full object-cover",loading:"lazy",onError:X=>{X.target.src='data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="200" height="200"%3E%3Crect fill="%23fef2f2" width="200" height="200"/%3E%3Ctext x="50%25" y="45%25" dominant-baseline="middle" text-anchor="middle" fill="%23dc2626" font-family="sans-serif" font-size="14"%3E加载失败%3C/text%3E%3Ctext x="50%25" y="60%25" dominant-baseline="middle" text-anchor="middle" fill="%23f87171" font-family="sans-serif" font-size="12"%3E请重新同步%3C/text%3E%3C/svg%3E',X.target.onerror=null}}),N.fileType&&N.fileType!=="image"&&k.jsxs("div",{className:`absolute top-2 right-2 rounded-md px-2 py-1 flex items-center gap-1 shadow-lg ${N.fileType==="video"?"bg-blue-500 bg-opacity-90":N.fileType==="audio"?"bg-pink-500 bg-opacity-90":N.fileType==="document"?"bg-green-500 bg-opacity-90":N.fileType==="design"?"bg-purple-500 bg-opacity-90":"bg-gray-500 bg-opacity-90"}`,children:[N.fileType==="video"&&k.jsx(By,{className:"w-4 h-4 text-white fill-white"}),N.fileType==="audio"&&k.jsx(Dy,{className:"w-4 h-4 text-white"}),N.fileType==="document"&&k.jsx(Ly,{className:"w-4 h-4 text-white"}),N.fileType==="design"&&k.jsx(Fy,{className:"w-4 h-4 text-white"}),N.fileType==="other"&&k.jsx(Oy,{className:"w-4 h-4 text-white"}),k.jsx("span",{className:"text-white text-xs font-semibold uppercase",children:N.format||N.filename.split(".").pop()})]}),k.jsx("div",{className:"absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-all pointer-events-none"})]}),k.jsx("div",{className:"mt-1 px-1",children:k.jsx("p",{className:"text-xs truncate text-center transition-colors",style:{color:q?"#3b82f6":"#909090",fontWeight:q?"600":"400"},children:N.filename})})]},N.id)},B=({index:N,style:V})=>{var q;const j=m[N];if(!j)return null;let W=0;for(let X=0;Xle(X,W+ne))})};return!x.length&&l.isLoading?k.jsx("div",{ref:c,className:"h-full overflow-hidden"}):x.length?!g&&x.length>0?k.jsx("div",{ref:c,className:"h-full overflow-hidden"}):k.jsxs("div",{ref:c,className:"h-full overflow-hidden",children:[k.jsx(dv,{images:Q,visible:z>=0,onClose:()=>O(-1),index:z,onIndexChange:O,children:Y?k.jsx(bv,{ref:d,height:b||600,width:g+32,itemCount:m.length,itemSize:$,className:"p-4",overscanCount:Is.overscanCount,onScroll:({scrollOffset:N,scrollDirection:V})=>{if(V==="forward"&&l.hasMore&&!l.isLoading){const j=m.reduce((q,X,ne)=>q+$(ne),0),W=N+(b||600);j-W{if(l.hasMore&&!l.isLoading){const{scrollTop:V,scrollHeight:j,clientHeight:W}=N.target;j-V-W{var W;let j=0;for(let q=0;qle(q,j+X))},V)})})})}),re&&k.jsx(Cv,{file:re,libraryId:e,onClose:()=>T(null)})]}):k.jsx("div",{ref:c,className:"flex items-center justify-center h-full text-gray-500 dark:text-gray-400",children:k.jsxs("div",{className:"text-center",children:[k.jsx("p",{className:"text-lg mb-2",children:"暂无图片"}),k.jsx("p",{className:"text-sm",children:"请添加素材库或调整搜索条件"})]})})}function Rv(){const{currentLibraryId:e,getCurrentLibrary:t}=rr(),{totalImageCount:r,folders:n}=_e(),i=t(),[s,o]=G.useState(0),a=n.length,l=n.filter(w=>!w.parentPath||w.parentPath==="."||w.parentPath==="");G.useEffect(()=>{e&&Le.getStats(e).then(w=>{o(w.totalSize||0)}).catch(w=>{console.error("Failed to fetch library stats:",w)})},[e,r]);const h=w=>{if(w===0)return"0 B";const y=1024,v=["B","KB","MB","GB","TB"],p=Math.floor(Math.log(w)/Math.log(y));return Math.round(w/Math.pow(y,p)*100)/100+" "+v[p]};return k.jsx("div",{className:"flex-1 h-full overflow-y-auto bg-gray-50 dark:bg-gray-900 p-8",children:k.jsxs("div",{className:"max-w-4xl mx-auto",children:[k.jsxs("div",{className:"mb-8",children:[k.jsx("h1",{className:"text-3xl font-bold text-gray-900 dark:text-white mb-2",children:(i==null?void 0:i.name)||"素材库"}),k.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:i==null?void 0:i.path})]}),k.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6 mb-12",children:[k.jsx("div",{className:"bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm border border-gray-100 dark:border-gray-700",children:k.jsxs("div",{className:"flex items-center gap-4",children:[k.jsx("div",{className:"p-3 bg-blue-100 dark:bg-blue-900/30 rounded-lg text-blue-600 dark:text-blue-400",children:k.jsx(My,{className:"w-6 h-6"})}),k.jsxs("div",{children:[k.jsx("div",{className:"text-2xl font-bold text-gray-900 dark:text-white",children:r.toLocaleString()}),k.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"总图片数"})]})]})}),k.jsx("div",{className:"bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm border border-gray-100 dark:border-gray-700",children:k.jsxs("div",{className:"flex items-center gap-4",children:[k.jsx("div",{className:"p-3 bg-indigo-100 dark:bg-indigo-900/30 rounded-lg text-indigo-600 dark:text-indigo-400",children:k.jsx(Di,{className:"w-6 h-6"})}),k.jsxs("div",{children:[k.jsx("div",{className:"text-2xl font-bold text-gray-900 dark:text-white",children:a.toLocaleString()}),k.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"文件夹"})]})]})}),k.jsx("div",{className:"bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm border border-gray-100 dark:border-gray-700",children:k.jsxs("div",{className:"flex items-center gap-4",children:[k.jsx("div",{className:"p-3 bg-purple-100 dark:bg-purple-900/30 rounded-lg text-purple-600 dark:text-purple-400",children:k.jsx(Py,{className:"w-6 h-6"})}),k.jsxs("div",{children:[k.jsx("div",{className:"text-2xl font-bold text-gray-900 dark:text-white",children:h(s)}),k.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"素材库大小"})]})]})})]}),l.length>0&&k.jsxs("div",{children:[k.jsx("h2",{className:"text-xl font-semibold text-gray-900 dark:text-white mb-4",children:"根目录文件夹"}),k.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",children:l.map(w=>k.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg p-4 shadow-sm border border-gray-100 dark:border-gray-700 hover:shadow-md transition-shadow cursor-pointer group",onClick:()=>_e.getState().setSelectedFolder(w.path),children:[k.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[k.jsx(Di,{className:"w-8 h-8 text-yellow-500 group-hover:text-yellow-400 transition-colors"}),k.jsx("div",{className:"flex-1 min-w-0",children:k.jsx("div",{className:"font-medium text-gray-900 dark:text-white truncate",title:w.name,children:w.name})})]}),k.jsxs("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:[w.imageCount||0," 张图片"]})]},w.path))})]}),l.length===0&&k.jsxs("div",{className:"text-center py-12 bg-white dark:bg-gray-800 rounded-xl border border-dashed border-gray-300 dark:border-gray-700",children:[k.jsx(Di,{className:"w-12 h-12 text-gray-300 dark:text-gray-600 mx-auto mb-4"}),k.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-white mb-2",children:"暂无文件夹"}),k.jsx("p",{className:"text-gray-500 dark:text-gray-400 max-w-sm mx-auto",children:"您的素材库似乎是空的。请将图片添加到素材库目录中,系统会自动扫描。"})]})]})})}function yd(){const{currentLibraryId:e}=rr(),{searchKeywords:t,filters:r,selectedFolder:n,setImages:i,imageLoadingState:s,images:o}=_e(),{scanProgress:a}=cn(),l=G.useRef(null),h=G.useRef(null),w=()=>{if(!a||a.current===0)return null;if(a.estimatedTimeLeft!==void 0){const p=a.estimatedTimeLeft;return p<1?"即将完成":p<60?`剩余约 ${p} 秒`:`剩余约 ${Math.floor(p/60)} 分钟`}return null},y=G.useCallback(()=>{jt.cancelAll(rs.IMAGES),l.current=null},[]),v=G.useCallback(async(p=!0)=>{var u;if(!e)return;if(!n&&!t&&r.formats.length===0){i([]),_e.getState().setImageLoadingState({isLoading:!1,loadedCount:0,totalCount:0,hasMore:!1});return}p&&sd.clear(),Cl(),y();const x=jt.createRequest(rs.IMAGES);l.current=x,_e.getState().setImageLoadingState({...s,isLoading:!0});try{const _={offset:p?0:s.loadedCount,limit:100};n&&(_.folder=n),t&&(_.keywords=t),((u=r.formats)==null?void 0:u.length)>0&&(_.formats=r.formats.join(","));const c=await Le.search(e,_,{signal:x.signal}),{images:d,total:g,hasMore:S}=c;if(!jt.isValid(x.id))return;jt.complete(x.id),p&&i(d),_e.getState().setImageLoadingState({isLoading:!1,loadedCount:d.length,totalCount:g,hasMore:S||!1}),S&&Vy(S)}catch(_){if(_.name==="CanceledError"||_.name==="AbortError")return;console.error("Error loading images:",_),jt.error(x.id)}finally{(jt.isValid(x.id)||x.status==="completed")&&(l.current=null)}},[e,t,r,n,i,y]);return G.useEffect(()=>{if(e)return h.current&&clearTimeout(h.current),y(),i([]),_e.getState().setImageLoadingState({isLoading:!0,loadedCount:0,totalCount:0,hasMore:!1}),sd.clear(),h.current=setTimeout(()=>{v(!0)},50),()=>{h.current&&clearTimeout(h.current)}},[e,t,r,n,v,y,i]),G.useEffect(()=>()=>{y(),h.current&&clearTimeout(h.current),Sl.cancelPendingLoads(),Sl.removeAllEventListeners()},[y]),k.jsxs("div",{className:"flex flex-col h-full bg-gray-50 dark:bg-gray-900",children:[a&&k.jsxs("div",{className:"p-4 border-b bg-blue-50 dark:bg-blue-900 border-blue-200 dark:border-blue-700",children:[k.jsxs("div",{className:"flex items-center justify-between mb-2",children:[k.jsx("div",{className:"text-sm font-medium text-blue-700 dark:text-blue-300",children:(a==null?void 0:a.status)==="preparing"?"正在准备扫描...":"正在扫描素材库..."}),k.jsxs("span",{className:"text-sm text-blue-600 dark:text-blue-400",children:[(a==null?void 0:a.percent)||0,"%"]})]}),k.jsx("div",{className:"w-full rounded-full h-2 mb-2 bg-blue-200 dark:bg-blue-800",children:k.jsx("div",{className:"h-2 rounded-full transition-all bg-blue-500",style:{width:`${(a==null?void 0:a.percent)||0}%`}})}),k.jsxs("div",{className:"text-xs text-blue-600 dark:text-blue-400",children:["已处理 ",(a==null?void 0:a.current)||0," / ",(a==null?void 0:a.total)||0," 张图片",w()&&` · ${w()}`]})]}),s.totalCount>0&&k.jsx("div",{className:"px-4 py-2 bg-gray-100 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700",children:k.jsxs("div",{className:"flex items-center justify-between text-sm",children:[k.jsxs("span",{className:"text-gray-600 dark:text-gray-400",children:["已加载 ",o.length," / ",s.totalCount," 张"]}),k.jsx("div",{className:"w-32 h-1.5 bg-gray-200 rounded-full overflow-hidden",children:k.jsx("div",{className:"h-full bg-blue-500",style:{width:`${s.totalCount?o.length/s.totalCount*100:0}%`}})})]})}),k.jsx("div",{className:"flex-1 overflow-hidden",children:!n&&!t&&r.formats.length===0?k.jsx(Rv,{}):k.jsx(Nv,{})})]})}function js(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var np={exports:{}};/*! + +JSZip v3.10.1 - A JavaScript class for generating and reading zip files + + +(c) 2009-2016 Stuart Knightley +Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. + +JSZip uses the library pako released under the MIT license : +https://github.com/nodeca/pako/blob/main/LICENSE +*/(function(e,t){(function(r){e.exports=r()})(function(){return function r(n,i,s){function o(h,w){if(!i[h]){if(!n[h]){var y=typeof js=="function"&&js;if(!w&&y)return y(h,!0);if(a)return a(h,!0);var v=new Error("Cannot find module '"+h+"'");throw v.code="MODULE_NOT_FOUND",v}var p=i[h]={exports:{}};n[h][0].call(p.exports,function(x){var u=n[h][1][x];return o(u||x)},p,p.exports,r,n,i,s)}return i[h].exports}for(var a=typeof js=="function"&&js,l=0;l>2,p=(3&h)<<4|w>>4,x=1>6:64,u=2>4,w=(15&v)<<4|(p=a.indexOf(l.charAt(u++)))>>2,y=(3&p)<<6|(x=a.indexOf(l.charAt(u++))),d[_++]=h,p!==64&&(d[_++]=w),x!==64&&(d[_++]=y);return d}},{"./support":30,"./utils":32}],2:[function(r,n,i){var s=r("./external"),o=r("./stream/DataWorker"),a=r("./stream/Crc32Probe"),l=r("./stream/DataLengthProbe");function h(w,y,v,p,x){this.compressedSize=w,this.uncompressedSize=y,this.crc32=v,this.compression=p,this.compressedContent=x}h.prototype={getContentWorker:function(){var w=new o(s.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new l("data_length")),y=this;return w.on("end",function(){if(this.streamInfo.data_length!==y.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),w},getCompressedWorker:function(){return new o(s.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},h.createWorkerFrom=function(w,y,v){return w.pipe(new a).pipe(new l("uncompressedSize")).pipe(y.compressWorker(v)).pipe(new l("compressedSize")).withStreamInfo("compression",y)},n.exports=h},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(r,n,i){var s=r("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new s("STORE compression")},uncompressWorker:function(){return new s("STORE decompression")}},i.DEFLATE=r("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(r,n,i){var s=r("./utils"),o=function(){for(var a,l=[],h=0;h<256;h++){a=h;for(var w=0;w<8;w++)a=1&a?3988292384^a>>>1:a>>>1;l[h]=a}return l}();n.exports=function(a,l){return a!==void 0&&a.length?s.getTypeOf(a)!=="string"?function(h,w,y,v){var p=o,x=v+y;h^=-1;for(var u=v;u>>8^p[255&(h^w[u])];return-1^h}(0|l,a,a.length,0):function(h,w,y,v){var p=o,x=v+y;h^=-1;for(var u=v;u>>8^p[255&(h^w.charCodeAt(u))];return-1^h}(0|l,a,a.length,0):0}},{"./utils":32}],5:[function(r,n,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(r,n,i){var s=null;s=typeof Promise<"u"?Promise:r("lie"),n.exports={Promise:s}},{lie:37}],7:[function(r,n,i){var s=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",o=r("pako"),a=r("./utils"),l=r("./stream/GenericWorker"),h=s?"uint8array":"array";function w(y,v){l.call(this,"FlateWorker/"+y),this._pako=null,this._pakoAction=y,this._pakoOptions=v,this.meta={}}i.magic="\b\0",a.inherits(w,l),w.prototype.processChunk=function(y){this.meta=y.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(h,y.data),!1)},w.prototype.flush=function(){l.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},w.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this._pako=null},w.prototype._createPako=function(){this._pako=new o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var y=this;this._pako.onData=function(v){y.push({data:v,meta:y.meta})}},i.compressWorker=function(y){return new w("Deflate",y)},i.uncompressWorker=function(){return new w("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(r,n,i){function s(p,x){var u,_="";for(u=0;u>>=8;return _}function o(p,x,u,_,c,d){var g,S,b=p.file,R=p.compression,z=d!==h.utf8encode,O=a.transformTo("string",d(b.name)),I=a.transformTo("string",h.utf8encode(b.name)),P=b.comment,re=a.transformTo("string",d(P)),T=a.transformTo("string",h.utf8encode(P)),H=I.length!==b.name.length,m=T.length!==P.length,K="",oe="",Q="",Y=b.dir,$=b.date,J={crc32:0,compressedSize:0,uncompressedSize:0};x&&!u||(J.crc32=p.crc32,J.compressedSize=p.compressedSize,J.uncompressedSize=p.uncompressedSize);var M=0;x&&(M|=8),z||!H&&!m||(M|=2048);var A=0,le=0;Y&&(A|=16),c==="UNIX"?(le=798,A|=function(N,V){var j=N;return N||(j=V?16893:33204),(65535&j)<<16}(b.unixPermissions,Y)):(le=20,A|=function(N){return 63&(N||0)}(b.dosPermissions)),g=$.getUTCHours(),g<<=6,g|=$.getUTCMinutes(),g<<=5,g|=$.getUTCSeconds()/2,S=$.getUTCFullYear()-1980,S<<=4,S|=$.getUTCMonth()+1,S<<=5,S|=$.getUTCDate(),H&&(oe=s(1,1)+s(w(O),4)+I,K+="up"+s(oe.length,2)+oe),m&&(Q=s(1,1)+s(w(re),4)+T,K+="uc"+s(Q.length,2)+Q);var B="";return B+=` +\0`,B+=s(M,2),B+=R.magic,B+=s(g,2),B+=s(S,2),B+=s(J.crc32,4),B+=s(J.compressedSize,4),B+=s(J.uncompressedSize,4),B+=s(O.length,2),B+=s(K.length,2),{fileRecord:y.LOCAL_FILE_HEADER+B+O+K,dirRecord:y.CENTRAL_FILE_HEADER+s(le,2)+B+s(re.length,2)+"\0\0\0\0"+s(A,4)+s(_,4)+O+K+re}}var a=r("../utils"),l=r("../stream/GenericWorker"),h=r("../utf8"),w=r("../crc32"),y=r("../signature");function v(p,x,u,_){l.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=x,this.zipPlatform=u,this.encodeFileName=_,this.streamFiles=p,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}a.inherits(v,l),v.prototype.push=function(p){var x=p.meta.percent||0,u=this.entriesCount,_=this._sources.length;this.accumulate?this.contentBuffer.push(p):(this.bytesWritten+=p.data.length,l.prototype.push.call(this,{data:p.data,meta:{currentFile:this.currentFile,percent:u?(x+100*(u-_-1))/u:100}}))},v.prototype.openedSource=function(p){this.currentSourceOffset=this.bytesWritten,this.currentFile=p.file.name;var x=this.streamFiles&&!p.file.dir;if(x){var u=o(p,x,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:u.fileRecord,meta:{percent:0}})}else this.accumulate=!0},v.prototype.closedSource=function(p){this.accumulate=!1;var x=this.streamFiles&&!p.file.dir,u=o(p,x,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(u.dirRecord),x)this.push({data:function(_){return y.DATA_DESCRIPTOR+s(_.crc32,4)+s(_.compressedSize,4)+s(_.uncompressedSize,4)}(p),meta:{percent:100}});else for(this.push({data:u.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},v.prototype.flush=function(){for(var p=this.bytesWritten,x=0;x=this.index;l--)h=(h<<8)+this.byteAt(l);return this.index+=a,h},readString:function(a){return s.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date(Date.UTC(1980+(a>>25&127),(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1))}},n.exports=o},{"../utils":32}],19:[function(r,n,i){var s=r("./Uint8ArrayReader");function o(a){s.call(this,a)}r("../utils").inherits(o,s),o.prototype.readData=function(a){this.checkOffset(a);var l=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},n.exports=o},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(r,n,i){var s=r("./DataReader");function o(a){s.call(this,a)}r("../utils").inherits(o,s),o.prototype.byteAt=function(a){return this.data.charCodeAt(this.zero+a)},o.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)-this.zero},o.prototype.readAndCheckSignature=function(a){return a===this.readData(4)},o.prototype.readData=function(a){this.checkOffset(a);var l=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},n.exports=o},{"../utils":32,"./DataReader":18}],21:[function(r,n,i){var s=r("./ArrayReader");function o(a){s.call(this,a)}r("../utils").inherits(o,s),o.prototype.readData=function(a){if(this.checkOffset(a),a===0)return new Uint8Array(0);var l=this.data.subarray(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},n.exports=o},{"../utils":32,"./ArrayReader":17}],22:[function(r,n,i){var s=r("../utils"),o=r("../support"),a=r("./ArrayReader"),l=r("./StringReader"),h=r("./NodeBufferReader"),w=r("./Uint8ArrayReader");n.exports=function(y){var v=s.getTypeOf(y);return s.checkSupport(v),v!=="string"||o.uint8array?v==="nodebuffer"?new h(y):o.uint8array?new w(s.transformTo("uint8array",y)):new a(s.transformTo("array",y)):new l(y)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(r,n,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(r,n,i){var s=r("./GenericWorker"),o=r("../utils");function a(l){s.call(this,"ConvertWorker to "+l),this.destType=l}o.inherits(a,s),a.prototype.processChunk=function(l){this.push({data:o.transformTo(this.destType,l.data),meta:l.meta})},n.exports=a},{"../utils":32,"./GenericWorker":28}],25:[function(r,n,i){var s=r("./GenericWorker"),o=r("../crc32");function a(){s.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}r("../utils").inherits(a,s),a.prototype.processChunk=function(l){this.streamInfo.crc32=o(l.data,this.streamInfo.crc32||0),this.push(l)},n.exports=a},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(r,n,i){var s=r("../utils"),o=r("./GenericWorker");function a(l){o.call(this,"DataLengthProbe for "+l),this.propName=l,this.withStreamInfo(l,0)}s.inherits(a,o),a.prototype.processChunk=function(l){if(l){var h=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=h+l.data.length}o.prototype.processChunk.call(this,l)},n.exports=a},{"../utils":32,"./GenericWorker":28}],27:[function(r,n,i){var s=r("../utils"),o=r("./GenericWorker");function a(l){o.call(this,"DataWorker");var h=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,l.then(function(w){h.dataIsReady=!0,h.data=w,h.max=w&&w.length||0,h.type=s.getTypeOf(w),h.isPaused||h._tickAndRepeat()},function(w){h.error(w)})}s.inherits(a,o),a.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this.data=null},a.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,s.delay(this._tickAndRepeat,[],this)),!0)},a.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(s.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},a.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var l=null,h=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":l=this.data.substring(this.index,h);break;case"uint8array":l=this.data.subarray(this.index,h);break;case"array":case"nodebuffer":l=this.data.slice(this.index,h)}return this.index=h,this.push({data:l,meta:{percent:this.max?this.index/this.max*100:0}})},n.exports=a},{"../utils":32,"./GenericWorker":28}],28:[function(r,n,i){function s(o){this.name=o||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}s.prototype={push:function(o){this.emit("data",o)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(o){this.emit("error",o)}return!0},error:function(o){return!this.isFinished&&(this.isPaused?this.generatedError=o:(this.isFinished=!0,this.emit("error",o),this.previous&&this.previous.error(o),this.cleanUp()),!0)},on:function(o,a){return this._listeners[o].push(a),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(o,a){if(this._listeners[o])for(var l=0;l "+o:o}},n.exports=s},{}],29:[function(r,n,i){var s=r("../utils"),o=r("./ConvertWorker"),a=r("./GenericWorker"),l=r("../base64"),h=r("../support"),w=r("../external"),y=null;if(h.nodestream)try{y=r("../nodejs/NodejsStreamOutputAdapter")}catch{}function v(x,u){return new w.Promise(function(_,c){var d=[],g=x._internalType,S=x._outputType,b=x._mimeType;x.on("data",function(R,z){d.push(R),u&&u(z)}).on("error",function(R){d=[],c(R)}).on("end",function(){try{var R=function(z,O,I){switch(z){case"blob":return s.newBlob(s.transformTo("arraybuffer",O),I);case"base64":return l.encode(O);default:return s.transformTo(z,O)}}(S,function(z,O){var I,P=0,re=null,T=0;for(I=0;I"u")i.blob=!1;else{var s=new ArrayBuffer(0);try{i.blob=new Blob([s],{type:"application/zip"}).size===0}catch{try{var o=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);o.append(s),i.blob=o.getBlob("application/zip").size===0}catch{i.blob=!1}}}try{i.nodestream=!!r("readable-stream").Readable}catch{i.nodestream=!1}},{"readable-stream":16}],31:[function(r,n,i){for(var s=r("./utils"),o=r("./support"),a=r("./nodejsUtils"),l=r("./stream/GenericWorker"),h=new Array(256),w=0;w<256;w++)h[w]=252<=w?6:248<=w?5:240<=w?4:224<=w?3:192<=w?2:1;h[254]=h[254]=1;function y(){l.call(this,"utf-8 decode"),this.leftOver=null}function v(){l.call(this,"utf-8 encode")}i.utf8encode=function(p){return o.nodebuffer?a.newBufferFrom(p,"utf-8"):function(x){var u,_,c,d,g,S=x.length,b=0;for(d=0;d>>6:(_<65536?u[g++]=224|_>>>12:(u[g++]=240|_>>>18,u[g++]=128|_>>>12&63),u[g++]=128|_>>>6&63),u[g++]=128|63&_);return u}(p)},i.utf8decode=function(p){return o.nodebuffer?s.transformTo("nodebuffer",p).toString("utf-8"):function(x){var u,_,c,d,g=x.length,S=new Array(2*g);for(u=_=0;u>10&1023,S[_++]=56320|1023&c)}return S.length!==_&&(S.subarray?S=S.subarray(0,_):S.length=_),s.applyFromCharCode(S)}(p=s.transformTo(o.uint8array?"uint8array":"array",p))},s.inherits(y,l),y.prototype.processChunk=function(p){var x=s.transformTo(o.uint8array?"uint8array":"array",p.data);if(this.leftOver&&this.leftOver.length){if(o.uint8array){var u=x;(x=new Uint8Array(u.length+this.leftOver.length)).set(this.leftOver,0),x.set(u,this.leftOver.length)}else x=this.leftOver.concat(x);this.leftOver=null}var _=function(d,g){var S;for((g=g||d.length)>d.length&&(g=d.length),S=g-1;0<=S&&(192&d[S])==128;)S--;return S<0||S===0?g:S+h[d[S]]>g?S:g}(x),c=x;_!==x.length&&(o.uint8array?(c=x.subarray(0,_),this.leftOver=x.subarray(_,x.length)):(c=x.slice(0,_),this.leftOver=x.slice(_,x.length))),this.push({data:i.utf8decode(c),meta:p.meta})},y.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=y,s.inherits(v,l),v.prototype.processChunk=function(p){this.push({data:i.utf8encode(p.data),meta:p.meta})},i.Utf8EncodeWorker=v},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(r,n,i){var s=r("./support"),o=r("./base64"),a=r("./nodejsUtils"),l=r("./external");function h(u){return u}function w(u,_){for(var c=0;c>8;this.dir=!!(16&this.externalFileAttributes),p==0&&(this.dosPermissions=63&this.externalFileAttributes),p==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var p=s(this.extraFields[1].value);this.uncompressedSize===o.MAX_VALUE_32BITS&&(this.uncompressedSize=p.readInt(8)),this.compressedSize===o.MAX_VALUE_32BITS&&(this.compressedSize=p.readInt(8)),this.localHeaderOffset===o.MAX_VALUE_32BITS&&(this.localHeaderOffset=p.readInt(8)),this.diskNumberStart===o.MAX_VALUE_32BITS&&(this.diskNumberStart=p.readInt(4))}},readExtraFields:function(p){var x,u,_,c=p.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});p.index+4>>6:(p<65536?v[_++]=224|p>>>12:(v[_++]=240|p>>>18,v[_++]=128|p>>>12&63),v[_++]=128|p>>>6&63),v[_++]=128|63&p);return v},i.buf2binstring=function(y){return w(y,y.length)},i.binstring2buf=function(y){for(var v=new s.Buf8(y.length),p=0,x=v.length;p>10&1023,d[x++]=56320|1023&u)}return w(d,x)},i.utf8border=function(y,v){var p;for((v=v||y.length)>y.length&&(v=y.length),p=v-1;0<=p&&(192&y[p])==128;)p--;return p<0||p===0?v:p+l[y[p]]>v?p:v}},{"./common":41}],43:[function(r,n,i){n.exports=function(s,o,a,l){for(var h=65535&s|0,w=s>>>16&65535|0,y=0;a!==0;){for(a-=y=2e3>>1:o>>>1;a[l]=o}return a}();n.exports=function(o,a,l,h){var w=s,y=h+l;o^=-1;for(var v=h;v>>8^w[255&(o^a[v])];return-1^o}},{}],46:[function(r,n,i){var s,o=r("../utils/common"),a=r("./trees"),l=r("./adler32"),h=r("./crc32"),w=r("./messages"),y=0,v=4,p=0,x=-2,u=-1,_=4,c=2,d=8,g=9,S=286,b=30,R=19,z=2*S+1,O=15,I=3,P=258,re=P+I+1,T=42,H=113,m=1,K=2,oe=3,Q=4;function Y(f,F){return f.msg=w[F],F}function $(f){return(f<<1)-(4f.avail_out&&(D=f.avail_out),D!==0&&(o.arraySet(f.output,F.pending_buf,F.pending_out,D,f.next_out),f.next_out+=D,F.pending_out+=D,f.total_out+=D,f.avail_out-=D,F.pending-=D,F.pending===0&&(F.pending_out=0))}function A(f,F){a._tr_flush_block(f,0<=f.block_start?f.block_start:-1,f.strstart-f.block_start,F),f.block_start=f.strstart,M(f.strm)}function le(f,F){f.pending_buf[f.pending++]=F}function B(f,F){f.pending_buf[f.pending++]=F>>>8&255,f.pending_buf[f.pending++]=255&F}function N(f,F){var D,E,C=f.max_chain_length,L=f.strstart,Z=f.prev_length,ee=f.nice_match,U=f.strstart>f.w_size-re?f.strstart-(f.w_size-re):0,ie=f.window,ue=f.w_mask,ae=f.prev,he=f.strstart+P,ve=ie[L+Z-1],me=ie[L+Z];f.prev_length>=f.good_match&&(C>>=2),ee>f.lookahead&&(ee=f.lookahead);do if(ie[(D=F)+Z]===me&&ie[D+Z-1]===ve&&ie[D]===ie[L]&&ie[++D]===ie[L+1]){L+=2,D++;do;while(ie[++L]===ie[++D]&&ie[++L]===ie[++D]&&ie[++L]===ie[++D]&&ie[++L]===ie[++D]&&ie[++L]===ie[++D]&&ie[++L]===ie[++D]&&ie[++L]===ie[++D]&&ie[++L]===ie[++D]&&LU&&--C!=0);return Z<=f.lookahead?Z:f.lookahead}function V(f){var F,D,E,C,L,Z,ee,U,ie,ue,ae=f.w_size;do{if(C=f.window_size-f.lookahead-f.strstart,f.strstart>=ae+(ae-re)){for(o.arraySet(f.window,f.window,ae,ae,0),f.match_start-=ae,f.strstart-=ae,f.block_start-=ae,F=D=f.hash_size;E=f.head[--F],f.head[F]=ae<=E?E-ae:0,--D;);for(F=D=ae;E=f.prev[--F],f.prev[F]=ae<=E?E-ae:0,--D;);C+=ae}if(f.strm.avail_in===0)break;if(Z=f.strm,ee=f.window,U=f.strstart+f.lookahead,ie=C,ue=void 0,ue=Z.avail_in,ie=I)for(L=f.strstart-f.insert,f.ins_h=f.window[L],f.ins_h=(f.ins_h<=I&&(f.ins_h=(f.ins_h<=I)if(E=a._tr_tally(f,f.strstart-f.match_start,f.match_length-I),f.lookahead-=f.match_length,f.match_length<=f.max_lazy_match&&f.lookahead>=I){for(f.match_length--;f.strstart++,f.ins_h=(f.ins_h<=I&&(f.ins_h=(f.ins_h<=I&&f.match_length<=f.prev_length){for(C=f.strstart+f.lookahead-I,E=a._tr_tally(f,f.strstart-1-f.prev_match,f.prev_length-I),f.lookahead-=f.prev_length-1,f.prev_length-=2;++f.strstart<=C&&(f.ins_h=(f.ins_h<f.pending_buf_size-5&&(D=f.pending_buf_size-5);;){if(f.lookahead<=1){if(V(f),f.lookahead===0&&F===y)return m;if(f.lookahead===0)break}f.strstart+=f.lookahead,f.lookahead=0;var E=f.block_start+D;if((f.strstart===0||f.strstart>=E)&&(f.lookahead=f.strstart-E,f.strstart=E,A(f,!1),f.strm.avail_out===0)||f.strstart-f.block_start>=f.w_size-re&&(A(f,!1),f.strm.avail_out===0))return m}return f.insert=0,F===v?(A(f,!0),f.strm.avail_out===0?oe:Q):(f.strstart>f.block_start&&(A(f,!1),f.strm.avail_out),m)}),new q(4,4,8,4,j),new q(4,5,16,8,j),new q(4,6,32,32,j),new q(4,4,16,16,W),new q(8,16,32,32,W),new q(8,16,128,128,W),new q(8,32,128,256,W),new q(32,128,258,1024,W),new q(32,258,258,4096,W)],i.deflateInit=function(f,F){return de(f,F,d,15,8,0)},i.deflateInit2=de,i.deflateReset=ce,i.deflateResetKeep=ne,i.deflateSetHeader=function(f,F){return f&&f.state?f.state.wrap!==2?x:(f.state.gzhead=F,p):x},i.deflate=function(f,F){var D,E,C,L;if(!f||!f.state||5>8&255),le(E,E.gzhead.time>>16&255),le(E,E.gzhead.time>>24&255),le(E,E.level===9?2:2<=E.strategy||E.level<2?4:0),le(E,255&E.gzhead.os),E.gzhead.extra&&E.gzhead.extra.length&&(le(E,255&E.gzhead.extra.length),le(E,E.gzhead.extra.length>>8&255)),E.gzhead.hcrc&&(f.adler=h(f.adler,E.pending_buf,E.pending,0)),E.gzindex=0,E.status=69):(le(E,0),le(E,0),le(E,0),le(E,0),le(E,0),le(E,E.level===9?2:2<=E.strategy||E.level<2?4:0),le(E,3),E.status=H);else{var Z=d+(E.w_bits-8<<4)<<8;Z|=(2<=E.strategy||E.level<2?0:E.level<6?1:E.level===6?2:3)<<6,E.strstart!==0&&(Z|=32),Z+=31-Z%31,E.status=H,B(E,Z),E.strstart!==0&&(B(E,f.adler>>>16),B(E,65535&f.adler)),f.adler=1}if(E.status===69)if(E.gzhead.extra){for(C=E.pending;E.gzindex<(65535&E.gzhead.extra.length)&&(E.pending!==E.pending_buf_size||(E.gzhead.hcrc&&E.pending>C&&(f.adler=h(f.adler,E.pending_buf,E.pending-C,C)),M(f),C=E.pending,E.pending!==E.pending_buf_size));)le(E,255&E.gzhead.extra[E.gzindex]),E.gzindex++;E.gzhead.hcrc&&E.pending>C&&(f.adler=h(f.adler,E.pending_buf,E.pending-C,C)),E.gzindex===E.gzhead.extra.length&&(E.gzindex=0,E.status=73)}else E.status=73;if(E.status===73)if(E.gzhead.name){C=E.pending;do{if(E.pending===E.pending_buf_size&&(E.gzhead.hcrc&&E.pending>C&&(f.adler=h(f.adler,E.pending_buf,E.pending-C,C)),M(f),C=E.pending,E.pending===E.pending_buf_size)){L=1;break}L=E.gzindexC&&(f.adler=h(f.adler,E.pending_buf,E.pending-C,C)),L===0&&(E.gzindex=0,E.status=91)}else E.status=91;if(E.status===91)if(E.gzhead.comment){C=E.pending;do{if(E.pending===E.pending_buf_size&&(E.gzhead.hcrc&&E.pending>C&&(f.adler=h(f.adler,E.pending_buf,E.pending-C,C)),M(f),C=E.pending,E.pending===E.pending_buf_size)){L=1;break}L=E.gzindexC&&(f.adler=h(f.adler,E.pending_buf,E.pending-C,C)),L===0&&(E.status=103)}else E.status=103;if(E.status===103&&(E.gzhead.hcrc?(E.pending+2>E.pending_buf_size&&M(f),E.pending+2<=E.pending_buf_size&&(le(E,255&f.adler),le(E,f.adler>>8&255),f.adler=0,E.status=H)):E.status=H),E.pending!==0){if(M(f),f.avail_out===0)return E.last_flush=-1,p}else if(f.avail_in===0&&$(F)<=$(D)&&F!==v)return Y(f,-5);if(E.status===666&&f.avail_in!==0)return Y(f,-5);if(f.avail_in!==0||E.lookahead!==0||F!==y&&E.status!==666){var ee=E.strategy===2?function(U,ie){for(var ue;;){if(U.lookahead===0&&(V(U),U.lookahead===0)){if(ie===y)return m;break}if(U.match_length=0,ue=a._tr_tally(U,0,U.window[U.strstart]),U.lookahead--,U.strstart++,ue&&(A(U,!1),U.strm.avail_out===0))return m}return U.insert=0,ie===v?(A(U,!0),U.strm.avail_out===0?oe:Q):U.last_lit&&(A(U,!1),U.strm.avail_out===0)?m:K}(E,F):E.strategy===3?function(U,ie){for(var ue,ae,he,ve,me=U.window;;){if(U.lookahead<=P){if(V(U),U.lookahead<=P&&ie===y)return m;if(U.lookahead===0)break}if(U.match_length=0,U.lookahead>=I&&0U.lookahead&&(U.match_length=U.lookahead)}if(U.match_length>=I?(ue=a._tr_tally(U,1,U.match_length-I),U.lookahead-=U.match_length,U.strstart+=U.match_length,U.match_length=0):(ue=a._tr_tally(U,0,U.window[U.strstart]),U.lookahead--,U.strstart++),ue&&(A(U,!1),U.strm.avail_out===0))return m}return U.insert=0,ie===v?(A(U,!0),U.strm.avail_out===0?oe:Q):U.last_lit&&(A(U,!1),U.strm.avail_out===0)?m:K}(E,F):s[E.level].func(E,F);if(ee!==oe&&ee!==Q||(E.status=666),ee===m||ee===oe)return f.avail_out===0&&(E.last_flush=-1),p;if(ee===K&&(F===1?a._tr_align(E):F!==5&&(a._tr_stored_block(E,0,0,!1),F===3&&(J(E.head),E.lookahead===0&&(E.strstart=0,E.block_start=0,E.insert=0))),M(f),f.avail_out===0))return E.last_flush=-1,p}return F!==v?p:E.wrap<=0?1:(E.wrap===2?(le(E,255&f.adler),le(E,f.adler>>8&255),le(E,f.adler>>16&255),le(E,f.adler>>24&255),le(E,255&f.total_in),le(E,f.total_in>>8&255),le(E,f.total_in>>16&255),le(E,f.total_in>>24&255)):(B(E,f.adler>>>16),B(E,65535&f.adler)),M(f),0=D.w_size&&(L===0&&(J(D.head),D.strstart=0,D.block_start=0,D.insert=0),ie=new o.Buf8(D.w_size),o.arraySet(ie,F,ue-D.w_size,D.w_size,0),F=ie,ue=D.w_size),Z=f.avail_in,ee=f.next_in,U=f.input,f.avail_in=ue,f.next_in=0,f.input=F,V(D);D.lookahead>=I;){for(E=D.strstart,C=D.lookahead-(I-1);D.ins_h=(D.ins_h<>>=I=O>>>24,g-=I,(I=O>>>16&255)===0)K[w++]=65535&O;else{if(!(16&I)){if(!(64&I)){O=S[(65535&O)+(d&(1<>>=I,g-=I),g<15&&(d+=m[l++]<>>=I=O>>>24,g-=I,!(16&(I=O>>>16&255))){if(!(64&I)){O=b[(65535&O)+(d&(1<>>=I,g-=I,(I=w-y)>3,d&=(1<<(g-=P<<3))-1,s.next_in=l,s.next_out=w,s.avail_in=l>>24&255)+(T>>>8&65280)+((65280&T)<<8)+((255&T)<<24)}function d(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function g(T){var H;return T&&T.state?(H=T.state,T.total_in=T.total_out=H.total=0,T.msg="",H.wrap&&(T.adler=1&H.wrap),H.mode=x,H.last=0,H.havedict=0,H.dmax=32768,H.head=null,H.hold=0,H.bits=0,H.lencode=H.lendyn=new s.Buf32(u),H.distcode=H.distdyn=new s.Buf32(_),H.sane=1,H.back=-1,v):p}function S(T){var H;return T&&T.state?((H=T.state).wsize=0,H.whave=0,H.wnext=0,g(T)):p}function b(T,H){var m,K;return T&&T.state?(K=T.state,H<0?(m=0,H=-H):(m=1+(H>>4),H<48&&(H&=15)),H&&(H<8||15=Q.wsize?(s.arraySet(Q.window,H,m-Q.wsize,Q.wsize,0),Q.wnext=0,Q.whave=Q.wsize):(K<(oe=Q.wsize-Q.wnext)&&(oe=K),s.arraySet(Q.window,H,m-K,oe,Q.wnext),(K-=oe)?(s.arraySet(Q.window,H,m-K,K,0),Q.wnext=K,Q.whave=Q.wsize):(Q.wnext+=oe,Q.wnext===Q.wsize&&(Q.wnext=0),Q.whave>>8&255,m.check=a(m.check,L,2,0),A=M=0,m.mode=2;break}if(m.flags=0,m.head&&(m.head.done=!1),!(1&m.wrap)||(((255&M)<<8)+(M>>8))%31){T.msg="incorrect header check",m.mode=30;break}if((15&M)!=8){T.msg="unknown compression method",m.mode=30;break}if(A-=4,f=8+(15&(M>>>=4)),m.wbits===0)m.wbits=f;else if(f>m.wbits){T.msg="invalid window size",m.mode=30;break}m.dmax=1<>8&1),512&m.flags&&(L[0]=255&M,L[1]=M>>>8&255,m.check=a(m.check,L,2,0)),A=M=0,m.mode=3;case 3:for(;A<32;){if($===0)break e;$--,M+=K[Q++]<>>8&255,L[2]=M>>>16&255,L[3]=M>>>24&255,m.check=a(m.check,L,4,0)),A=M=0,m.mode=4;case 4:for(;A<16;){if($===0)break e;$--,M+=K[Q++]<>8),512&m.flags&&(L[0]=255&M,L[1]=M>>>8&255,m.check=a(m.check,L,2,0)),A=M=0,m.mode=5;case 5:if(1024&m.flags){for(;A<16;){if($===0)break e;$--,M+=K[Q++]<>>8&255,m.check=a(m.check,L,2,0)),A=M=0}else m.head&&(m.head.extra=null);m.mode=6;case 6:if(1024&m.flags&&($<(N=m.length)&&(N=$),N&&(m.head&&(f=m.head.extra_len-m.length,m.head.extra||(m.head.extra=new Array(m.head.extra_len)),s.arraySet(m.head.extra,K,Q,N,f)),512&m.flags&&(m.check=a(m.check,K,N,Q)),$-=N,Q+=N,m.length-=N),m.length))break e;m.length=0,m.mode=7;case 7:if(2048&m.flags){if($===0)break e;for(N=0;f=K[Q+N++],m.head&&f&&m.length<65536&&(m.head.name+=String.fromCharCode(f)),f&&N<$;);if(512&m.flags&&(m.check=a(m.check,K,N,Q)),$-=N,Q+=N,f)break e}else m.head&&(m.head.name=null);m.length=0,m.mode=8;case 8:if(4096&m.flags){if($===0)break e;for(N=0;f=K[Q+N++],m.head&&f&&m.length<65536&&(m.head.comment+=String.fromCharCode(f)),f&&N<$;);if(512&m.flags&&(m.check=a(m.check,K,N,Q)),$-=N,Q+=N,f)break e}else m.head&&(m.head.comment=null);m.mode=9;case 9:if(512&m.flags){for(;A<16;){if($===0)break e;$--,M+=K[Q++]<>9&1,m.head.done=!0),T.adler=m.check=0,m.mode=12;break;case 10:for(;A<32;){if($===0)break e;$--,M+=K[Q++]<>>=7&A,A-=7&A,m.mode=27;break}for(;A<3;){if($===0)break e;$--,M+=K[Q++]<>>=1)){case 0:m.mode=14;break;case 1:if(P(m),m.mode=20,H!==6)break;M>>>=2,A-=2;break e;case 2:m.mode=17;break;case 3:T.msg="invalid block type",m.mode=30}M>>>=2,A-=2;break;case 14:for(M>>>=7&A,A-=7&A;A<32;){if($===0)break e;$--,M+=K[Q++]<>>16^65535)){T.msg="invalid stored block lengths",m.mode=30;break}if(m.length=65535&M,A=M=0,m.mode=15,H===6)break e;case 15:m.mode=16;case 16:if(N=m.length){if($>>=5,A-=5,m.ndist=1+(31&M),M>>>=5,A-=5,m.ncode=4+(15&M),M>>>=4,A-=4,286>>=3,A-=3}for(;m.have<19;)m.lens[Z[m.have++]]=0;if(m.lencode=m.lendyn,m.lenbits=7,D={bits:m.lenbits},F=h(0,m.lens,0,19,m.lencode,0,m.work,D),m.lenbits=D.bits,F){T.msg="invalid code lengths set",m.mode=30;break}m.have=0,m.mode=19;case 19:for(;m.have>>16&255,X=65535&C,!((W=C>>>24)<=A);){if($===0)break e;$--,M+=K[Q++]<>>=W,A-=W,m.lens[m.have++]=X;else{if(X===16){for(E=W+2;A>>=W,A-=W,m.have===0){T.msg="invalid bit length repeat",m.mode=30;break}f=m.lens[m.have-1],N=3+(3&M),M>>>=2,A-=2}else if(X===17){for(E=W+3;A>>=W)),M>>>=3,A-=3}else{for(E=W+7;A>>=W)),M>>>=7,A-=7}if(m.have+N>m.nlen+m.ndist){T.msg="invalid bit length repeat",m.mode=30;break}for(;N--;)m.lens[m.have++]=f}}if(m.mode===30)break;if(m.lens[256]===0){T.msg="invalid code -- missing end-of-block",m.mode=30;break}if(m.lenbits=9,D={bits:m.lenbits},F=h(w,m.lens,0,m.nlen,m.lencode,0,m.work,D),m.lenbits=D.bits,F){T.msg="invalid literal/lengths set",m.mode=30;break}if(m.distbits=6,m.distcode=m.distdyn,D={bits:m.distbits},F=h(y,m.lens,m.nlen,m.ndist,m.distcode,0,m.work,D),m.distbits=D.bits,F){T.msg="invalid distances set",m.mode=30;break}if(m.mode=20,H===6)break e;case 20:m.mode=21;case 21:if(6<=$&&258<=J){T.next_out=Y,T.avail_out=J,T.next_in=Q,T.avail_in=$,m.hold=M,m.bits=A,l(T,B),Y=T.next_out,oe=T.output,J=T.avail_out,Q=T.next_in,K=T.input,$=T.avail_in,M=m.hold,A=m.bits,m.mode===12&&(m.back=-1);break}for(m.back=0;q=(C=m.lencode[M&(1<>>16&255,X=65535&C,!((W=C>>>24)<=A);){if($===0)break e;$--,M+=K[Q++]<>ne)])>>>16&255,X=65535&C,!(ne+(W=C>>>24)<=A);){if($===0)break e;$--,M+=K[Q++]<>>=ne,A-=ne,m.back+=ne}if(M>>>=W,A-=W,m.back+=W,m.length=X,q===0){m.mode=26;break}if(32&q){m.back=-1,m.mode=12;break}if(64&q){T.msg="invalid literal/length code",m.mode=30;break}m.extra=15&q,m.mode=22;case 22:if(m.extra){for(E=m.extra;A>>=m.extra,A-=m.extra,m.back+=m.extra}m.was=m.length,m.mode=23;case 23:for(;q=(C=m.distcode[M&(1<>>16&255,X=65535&C,!((W=C>>>24)<=A);){if($===0)break e;$--,M+=K[Q++]<>ne)])>>>16&255,X=65535&C,!(ne+(W=C>>>24)<=A);){if($===0)break e;$--,M+=K[Q++]<>>=ne,A-=ne,m.back+=ne}if(M>>>=W,A-=W,m.back+=W,64&q){T.msg="invalid distance code",m.mode=30;break}m.offset=X,m.extra=15&q,m.mode=24;case 24:if(m.extra){for(E=m.extra;A>>=m.extra,A-=m.extra,m.back+=m.extra}if(m.offset>m.dmax){T.msg="invalid distance too far back",m.mode=30;break}m.mode=25;case 25:if(J===0)break e;if(N=B-J,m.offset>N){if((N=m.offset-N)>m.whave&&m.sane){T.msg="invalid distance too far back",m.mode=30;break}V=N>m.wnext?(N-=m.wnext,m.wsize-N):m.wnext-N,N>m.length&&(N=m.length),j=m.window}else j=oe,V=Y-m.offset,N=m.length;for(Jz?(I=V[j+_[H]],A[le+_[H]]):(I=96,0),d=1<>Y)+(g-=d)]=O<<24|I<<16|P|0,g!==0;);for(d=1<>=1;if(d!==0?(M&=d-1,M+=d):M=0,H++,--B[T]==0){if(T===K)break;T=y[v+_[H]]}if(oe>>7)]}function le(C,L){C.pending_buf[C.pending++]=255&L,C.pending_buf[C.pending++]=L>>>8&255}function B(C,L,Z){C.bi_valid>c-Z?(C.bi_buf|=L<>c-C.bi_valid,C.bi_valid+=Z-c):(C.bi_buf|=L<>>=1,Z<<=1,0<--L;);return Z>>>1}function j(C,L,Z){var ee,U,ie=new Array(_+1),ue=0;for(ee=1;ee<=_;ee++)ie[ee]=ue=ue+Z[ee-1]<<1;for(U=0;U<=L;U++){var ae=C[2*U+1];ae!==0&&(C[2*U]=V(ie[ae]++,ae))}}function W(C){var L;for(L=0;L>1;1<=Z;Z--)ne(C,ie,Z);for(U=he;Z=C.heap[1],C.heap[1]=C.heap[C.heap_len--],ne(C,ie,1),ee=C.heap[1],C.heap[--C.heap_max]=Z,C.heap[--C.heap_max]=ee,ie[2*U]=ie[2*Z]+ie[2*ee],C.depth[U]=(C.depth[Z]>=C.depth[ee]?C.depth[Z]:C.depth[ee])+1,ie[2*Z+1]=ie[2*ee+1]=U,C.heap[1]=U++,ne(C,ie,1),2<=C.heap_len;);C.heap[--C.heap_max]=C.heap[1],function(me,Ve){var Kt,nt,Yt,xe,ar,Zt,Ge=Ve.dyn_tree,Tr=Ve.max_code,bn=Ve.stat_desc.static_tree,bt=Ve.stat_desc.has_stree,ge=Ve.stat_desc.extra_bits,Ee=Ve.stat_desc.extra_base,Te=Ve.stat_desc.max_length,ze=0;for(xe=0;xe<=_;xe++)me.bl_count[xe]=0;for(Ge[2*me.heap[me.heap_max]+1]=0,Kt=me.heap_max+1;Kt>=7;U>>=1)if(1&ve&&ae.dyn_ltree[2*he]!==0)return o;if(ae.dyn_ltree[18]!==0||ae.dyn_ltree[20]!==0||ae.dyn_ltree[26]!==0)return a;for(he=32;he>>3,(ie=C.static_len+3+7>>>3)<=U&&(U=ie)):U=ie=Z+5,Z+4<=U&&L!==-1?E(C,L,Z,ee):C.strategy===4||ie===U?(B(C,2+(ee?1:0),3),ce(C,re,T)):(B(C,4+(ee?1:0),3),function(ae,he,ve,me){var Ve;for(B(ae,he-257,5),B(ae,ve-1,5),B(ae,me-4,4),Ve=0;Ve>>8&255,C.pending_buf[C.d_buf+2*C.last_lit+1]=255&L,C.pending_buf[C.l_buf+C.last_lit]=255&Z,C.last_lit++,L===0?C.dyn_ltree[2*Z]++:(C.matches++,L--,C.dyn_ltree[2*(m[Z]+y+1)]++,C.dyn_dtree[2*A(L)]++),C.last_lit===C.lit_bufsize-1},i._tr_align=function(C){B(C,2,3),N(C,g,re),function(L){L.bi_valid===16?(le(L,L.bi_buf),L.bi_buf=0,L.bi_valid=0):8<=L.bi_valid&&(L.pending_buf[L.pending++]=255&L.bi_buf,L.bi_buf>>=8,L.bi_valid-=8)}(C)}},{"../utils/common":41}],53:[function(r,n,i){n.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(r,n,i){(function(s){(function(o,a){if(!o.setImmediate){var l,h,w,y,v=1,p={},x=!1,u=o.document,_=Object.getPrototypeOf&&Object.getPrototypeOf(o);_=_&&_.setTimeout?_:o,l={}.toString.call(o.process)==="[object process]"?function(S){process.nextTick(function(){d(S)})}:function(){if(o.postMessage&&!o.importScripts){var S=!0,b=o.onmessage;return o.onmessage=function(){S=!1},o.postMessage("","*"),o.onmessage=b,S}}()?(y="setImmediate$"+Math.random()+"$",o.addEventListener?o.addEventListener("message",g,!1):o.attachEvent("onmessage",g),function(S){o.postMessage(y+S,"*")}):o.MessageChannel?((w=new MessageChannel).port1.onmessage=function(S){d(S.data)},function(S){w.port2.postMessage(S)}):u&&"onreadystatechange"in u.createElement("script")?(h=u.documentElement,function(S){var b=u.createElement("script");b.onreadystatechange=function(){d(S),b.onreadystatechange=null,h.removeChild(b),b=null},h.appendChild(b)}):function(S){setTimeout(d,0,S)},_.setImmediate=function(S){typeof S!="function"&&(S=new Function(""+S));for(var b=new Array(arguments.length-1),R=0;R"u"?s===void 0?this:s:self)}).call(this,typeof us<"u"?us:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(np);var Tv=np.exports;const vd=Il(Tv);function wd(){const{currentLibraryId:e}=rr(),{selectedImage:t,selectedImages:r,selectedFolder:n,images:i}=_e(),{setMobileView:s,isResizingPanels:o,resizingSide:a}=yt(),[l,h]=G.useState(!1),[w,y]=G.useState(""),[v,p]=G.useState(!1),[x,u]=G.useState(!1),[_,c]=G.useState(!1),[d,g]=G.useState(0),[S,b]=G.useState(!1),[R,z]=G.useState(0),O=r.length>0?t&&!r.some(N=>N.id===t.id)?r.length+1:r.length:t?1:0,I=O>1,P=r.length>0?r[0]:t;if(G.useEffect(()=>{const N=()=>{h(window.innerWidth<768)};return N(),window.addEventListener("resize",N),()=>window.removeEventListener("resize",N)},[]),G.useEffect(()=>{if(!t||!e){y("");return}const N=re();if(y(N),p(!0),o){p(!1);return}const V=T(),j=new Image;return j.onload=()=>{y(V),p(!1)},j.onerror=()=>{console.error("Failed to load original image"),p(!1)},j.src=V,()=>{j.onload=null,j.onerror=null}},[t,e,o,a]),!t&&r.length===0)return k.jsx("div",{className:"w-full border-l border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 flex items-center justify-center",children:k.jsx("p",{className:"text-gray-400 dark:text-gray-500 text-sm",children:"选择图片查看详情"})});const re=()=>{if(!e||!(t!=null&&t.thumbnail_path))return"";const N=t.thumbnail_path.replace(/\\/g,"/").split("/").pop();return Le.getThumbnailUrl(e,N)},T=()=>!e||!(t!=null&&t.path)?"":Le.getOriginalUrl(e,t.path),H=()=>typeof ClipboardItem<"u"&&navigator.clipboard&&typeof navigator.clipboard.write=="function",m=async N=>new Promise(V=>{const j=document.createElement("div");j.setAttribute("contenteditable","true"),j.style.position="fixed",j.style.left="-9999px",j.style.top="-9999px",j.style.opacity="0",document.body.appendChild(j);const W=document.createElement("img");W.crossOrigin="anonymous",W.onload=()=>{j.appendChild(W);const q=document.createRange();q.selectNodeContents(j);const X=window.getSelection();X.removeAllRanges(),X.addRange(q);let ne=!1;try{ne=document.execCommand("copy")}catch(ce){console.error("execCommand copy 失败:",ce)}X.removeAllRanges(),document.body.removeChild(j),V(ne)},W.onerror=()=>{document.body.removeChild(j),V(!1)},W.src=N}),K=async N=>new Promise(async V=>{try{const W=await(await fetch(N)).blob(),q=new Image;q.crossOrigin="anonymous";const X=new Promise((L,Z)=>{q.onload=L,q.onerror=Z});q.src=URL.createObjectURL(W),await X;const ne=document.createElement("canvas");ne.width=q.width,ne.height=q.height,ne.getContext("2d").drawImage(q,0,0),URL.revokeObjectURL(q.src);const de=ne.toDataURL("image/png"),f=document.createElement("div");f.setAttribute("contenteditable","true"),f.style.position="fixed",f.style.left="-9999px",f.style.top="-9999px",f.style.opacity="0",document.body.appendChild(f);const F=document.createElement("img");F.src=de,f.appendChild(F),await new Promise(L=>setTimeout(L,50));const D=document.createRange();D.selectNodeContents(f);const E=window.getSelection();E.removeAllRanges(),E.addRange(D);let C=!1;try{C=document.execCommand("copy")}catch(L){console.error("execCommand copy 失败:",L)}E.removeAllRanges(),document.body.removeChild(f),V(C)}catch(j){console.error("Canvas 复制失败:",j),V(!1)}}),oe=N=>{const V=document.createElement("textarea");V.value=N,V.style.position="fixed",V.style.left="-9999px",V.style.top="-9999px",document.body.appendChild(V),V.focus(),V.select();try{return document.execCommand("copy"),!0}catch(j){return console.error("execCommand 复制失败:",j),!1}finally{document.body.removeChild(V)}},Q=async()=>{try{const N=Le.getOriginalUrl(e,t.path);if(H())try{const X=await(await fetch(N)).blob(),ne=new Image,ce=new Promise((E,C)=>{ne.onload=E,ne.onerror=C});ne.src=URL.createObjectURL(X),await ce;const de=document.createElement("canvas");de.width=ne.width,de.height=ne.height,de.getContext("2d").drawImage(ne,0,0),URL.revokeObjectURL(ne.src);const F=await new Promise(E=>{de.toBlob(E,"image/png")}),D=new ClipboardItem({"image/png":F});await navigator.clipboard.write([D]),u(!0),setTimeout(()=>u(!1),2e3);return}catch(q){console.warn("Clipboard API 失败,尝试备用方案:",q)}if(console.log("尝试 Canvas + execCommand 方案..."),await K(N)){u(!0),setTimeout(()=>u(!1),2e3);return}if(console.log("尝试直接图片 URL 方案..."),await m(N)){u(!0),setTimeout(()=>u(!1),2e3);return}console.warn("所有图片复制方案失败,降级为复制链接"),oe(N)?(u(!0),setTimeout(()=>u(!1),2e3),alert(`已复制图片链接到剪贴板 +(当前浏览器环境限制,无法直接复制图片)`)):alert(`复制失败,请手动复制图片链接: +`+N)}catch(N){console.error("复制图片失败:",N),alert("复制图片失败,请重试")}},Y=async N=>new Promise(async V=>{try{const j=document.createElement("div");j.setAttribute("contenteditable","true"),j.style.position="fixed",j.style.left="-9999px",j.style.top="-9999px",j.style.opacity="0",document.body.appendChild(j);for(const{url:ne,filename:ce}of N)try{const f=await(await fetch(ne)).blob(),F=new Image;F.crossOrigin="anonymous",await new Promise((Z,ee)=>{F.onload=Z,F.onerror=ee,F.src=URL.createObjectURL(f)});const D=document.createElement("canvas");D.width=F.width,D.height=F.height,D.getContext("2d").drawImage(F,0,0),URL.revokeObjectURL(F.src);const C=D.toDataURL("image/png"),L=document.createElement("img");L.src=C,L.alt=ce,L.style.display="block",L.style.marginBottom="10px",j.appendChild(L)}catch(de){console.error(`加载图片失败: ${ce}`,de)}await new Promise(ne=>setTimeout(ne,100));const W=document.createRange();W.selectNodeContents(j);const q=window.getSelection();q.removeAllRanges(),q.addRange(W);let X=!1;try{X=document.execCommand("copy")}catch(ne){console.error("execCommand copy 失败:",ne)}q.removeAllRanges(),document.body.removeChild(j),V(X)}catch(j){console.error("批量复制图片失败:",j),V(!1)}}),$=()=>r.length>0?t&&!r.some(N=>N.id===t.id)?[t,...r]:r:t?[t]:[],J=async()=>{try{const N=$();if(N.length===1){await Q();return}const V=N.map(X=>({url:Le.getOriginalUrl(e,X.path),filename:X.filename})),j=N.map(X=>X.filename).join(` +`);if(H())try{const ne=(await Promise.all(N.map(async ce=>{const de=Le.getOriginalUrl(e,ce.path),F=await(await fetch(de)).blob();return new Promise(D=>{const E=new FileReader;E.onloadend=()=>{D({dataUrl:E.result,filename:ce.filename})},E.readAsDataURL(F)})}))).map(({dataUrl:ce,filename:de})=>`${de}`).join(` +`);await navigator.clipboard.write([new ClipboardItem({"text/html":new Blob([ne],{type:"text/html"}),"text/plain":new Blob([j],{type:"text/plain"})})]),u(!0),setTimeout(()=>u(!1),2e3);return}catch(X){console.warn("Clipboard API 失败,尝试备用方案:",X)}if(console.log("尝试 contenteditable 批量复制方案..."),await Y(V)){u(!0),setTimeout(()=>u(!1),2e3);return}console.warn("批量图片复制失败,降级为复制文件名"),oe(j)?(u(!0),setTimeout(()=>u(!1),2e3),alert(`已复制 ${N.length} 个文件名到剪贴板 +(当前环境限制,建议使用"导出"功能)`)):alert('复制失败,请使用"导出"功能下载图片')}catch(N){console.error("复制图片失败:",N),alert("复制图片失败,请重试")}},M=async()=>{c(!0);try{const N=$();if(N.length===1){const V=Le.getOriginalUrl(e,N[0].path),j=document.createElement("a");j.href=V,j.download=N[0].filename,j.target="_blank",document.body.appendChild(j),j.click(),document.body.removeChild(j)}else{const V=new vd,j=V.folder("images");g(0);for(let X=0;X{if(!n){alert("请先选择一个文件夹");return}b(!0),z(0);try{const N=i.filter(ne=>ne.folder&&ne.folder.startsWith(n));if(N.length===0){alert("当前文件夹没有图片");return}const V=new vd,j=n.split("/").pop()||"images",W=V.folder(j);for(let ne=0;neN<1024?N+" B":N<1024*1024?(N/1024).toFixed(2)+" KB":(N/(1024*1024)).toFixed(2)+" MB",B=N=>new Date(N).toLocaleString("zh-CN");return k.jsxs("div",{className:"w-full border-l border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 flex flex-col h-full",children:[l&&k.jsx("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700 flex items-center",children:k.jsxs("button",{onClick:()=>s("main"),className:"flex items-center gap-2 text-gray-700 dark:text-gray-300 hover:text-blue-500",children:[k.jsx(Cy,{className:"w-5 h-5"}),k.jsx("span",{className:"text-sm font-medium",children:"返回"})]})}),k.jsx("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0",children:k.jsxs("div",{className:"w-full aspect-square bg-gray-100 dark:bg-gray-700 rounded-lg overflow-hidden relative",children:[k.jsx("img",{src:w,alt:P.filename,decoding:"async",className:`w-full h-full object-contain transition-opacity duration-300 ${v?"opacity-75":"opacity-100"}`}),v&&k.jsx("div",{className:"absolute top-2 right-2 bg-blue-500 text-white text-xs px-2 py-1 rounded",children:"加载原图中..."})]})}),k.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 min-h-0",children:k.jsxs("div",{children:[k.jsx("h3",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2",children:"基本信息"}),k.jsxs("div",{className:"space-y-2 text-sm",children:[k.jsxs("div",{children:[k.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"文件名:"}),k.jsx("p",{className:"text-gray-900 dark:text-gray-100 break-all",children:t.filename})]}),k.jsxs("div",{children:[k.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"尺寸:"}),k.jsxs("p",{className:"text-gray-900 dark:text-gray-100",children:[t.width," × ",t.height]})]}),k.jsxs("div",{children:[k.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"大小:"}),k.jsx("p",{className:"text-gray-900 dark:text-gray-100",children:le(t.size)})]}),k.jsxs("div",{children:[k.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"格式:"}),k.jsx("p",{className:"text-gray-900 dark:text-gray-100 uppercase",children:t.format})]}),k.jsxs("div",{children:[k.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"创建时间:"}),k.jsx("p",{className:"text-gray-900 dark:text-gray-100",children:B(t.created_at)})]}),k.jsxs("div",{children:[k.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"修改时间:"}),k.jsx("p",{className:"text-gray-900 dark:text-gray-100",children:B(t.modified_at)})]}),k.jsxs("div",{children:[k.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"路径:"}),k.jsx("p",{className:"text-gray-900 dark:text-gray-100 text-xs break-all",children:t.path})]})]})]})}),!l&&k.jsxs("div",{className:"p-4 border-t border-gray-200 dark:border-gray-700 space-y-2 flex-shrink-0",children:[k.jsx("button",{onClick:J,className:`w-full flex items-center justify-center gap-2 px-4 py-2 rounded-lg transition-all ${x?"bg-green-500 text-white":"bg-blue-500 text-white hover:bg-blue-600"}`,children:x?k.jsxs(k.Fragment,{children:[k.jsx(Ey,{className:"w-4 h-4"}),k.jsxs("span",{children:["已复制",I?` ${O} 张`:""]})]}):k.jsxs(k.Fragment,{children:[k.jsx(zy,{className:"w-4 h-4"}),k.jsxs("span",{children:["复制图片",I?` (${O})`:""]})]})}),k.jsxs("button",{onClick:M,disabled:_,className:"w-full flex flex-col items-center justify-center gap-2 px-4 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[k.jsxs("div",{className:"flex items-center gap-2",children:[k.jsx(Iy,{className:"w-4 h-4"}),k.jsx("span",{children:_?`打包中... ${d}%`:`导出图片${I?` (${O})`:""}`})]}),_&&I&&k.jsx("div",{className:"w-full bg-gray-300 dark:bg-gray-600 rounded-full h-1.5 mt-1",children:k.jsx("div",{className:"bg-blue-500 h-1.5 rounded-full transition-all duration-300",style:{width:`${d}%`}})})]}),n&&k.jsxs("button",{onClick:A,disabled:S,className:"w-full flex flex-col items-center justify-center gap-2 px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[k.jsxs("div",{className:"flex items-center gap-2",children:[k.jsx(Ay,{className:"w-4 h-4"}),k.jsx("span",{children:S?`打包文件夹... ${R}%`:"导出当前文件夹"})]}),S&&k.jsx("div",{className:"w-full bg-purple-300 rounded-full h-1.5 mt-1",children:k.jsx("div",{className:"bg-white h-1.5 rounded-full transition-all duration-300",style:{width:`${R}%`}})})]})]})]})}function xd(){const{currentLibraryId:e}=rr(),{searchKeywords:t,images:r,selectedFolder:n,setSearchKeywords:i}=_e(),{theme:s,toggleTheme:o,thumbnailHeight:a,setThumbnailHeight:l,mobileView:h}=yt(),[w,y]=G.useState(!1),[v,p]=G.useState([]),[x,u]=G.useState([]),[_,c]=G.useState(""),[d,g]=G.useState(!1),[S,b]=G.useState(!1),[R,z]=G.useState(!1),[O,I]=G.useState(t),P=G.useRef(null);G.useEffect(()=>{const j=()=>{b(window.innerWidth<768)};return j(),window.addEventListener("resize",j),()=>window.removeEventListener("resize",j)},[]),G.useEffect(()=>{p([]),u([]),c("")},[n]);const re=j=>{I(j),P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{i(j)},300)};G.useEffect(()=>{I(t)},[t]),G.useEffect(()=>()=>{P.current&&clearTimeout(P.current)},[]);const T=j=>{if(j.length===0)return[];const W=[...j].sort((D,E)=>D-E),q=W[0],X=W[W.length-1];if(X-q<10)return[H(q,X)];const ne=5,ce=[],de=Math.log10(q||1),F=(Math.log10(X)-de)/ne;for(let D=0;DZ>=E&&ZD)},H=(j,W,q=!1)=>{const X=ne=>{const ce=de=>de<10?Math.round(de):de<100?Math.round(de/5)*5:de<1e3?Math.round(de/10)*10:Math.round(de/50)*50;return ne<1?`${ce(ne*1024)}B`:ne<1024?`${ce(ne)}KB`:ne<1048576?`${ce(ne/1024)}MB`:`${ce(ne/1048576)}GB`};return q?`> ${X(j)}`:`${X(j)} - ${X(W)}`},m=j=>{const W=j.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB)$/);if(!W)return 0;const q=parseFloat(W[1]);switch(W[2]){case"B":return q/1024;case"KB":return q;case"MB":return q*1024;case"GB":return q*1024*1024;default:return 0}},K=(j,W)=>{if(W.startsWith(">")){const q=W.substring(1).trim(),X=m(q);return j>=X}else if(W.includes(" - ")){const[q,X]=W.split(" - ").map(de=>de.trim()),ne=m(q),ce=m(X);return j>=ne&&j{if(r.length===0)return{formats:[],sizes:[],hasHorizontal:!1,hasVertical:!1};const j=new Set,W=[];let q=!1,X=!1;r.forEach(ce=>{ce.format&&j.add(ce.format.toLowerCase()),W.push(ce.size/1024),ce.width>ce.height&&(q=!0),ce.height>ce.width&&(X=!0)});const ne=T(W);return{formats:Array.from(j).sort(),sizes:ne,hasHorizontal:q,hasVertical:X}},[r]);G.useMemo(()=>{if(v.length===0&&x.length===0&&!_)return r;const j=new Set(v),W=new Set(x);return r.filter(q=>{var X;if(j.size>0&&!j.has((X=q.format)==null?void 0:X.toLowerCase()))return!1;if(W.size>0){const ne=q.size/1024;let ce=!1;for(const de of W)if(K(ne,de)){ce=!0;break}if(!ce)return!1}if(_==="horizontal"){if(q.width<=q.height)return!1}else if(_==="vertical"&&q.height<=q.width)return!1;return!0})},[r,v,x,_]);const Q=j=>{p(W=>W.includes(j)?W.filter(q=>q!==j):[...W,j])},Y=j=>{u(W=>W.includes(j)?W.filter(q=>q!==j):[...W,j])},$=j=>{c(W=>W===j?"":j)},J=()=>{p([]),u([]),c("")},M=async()=>{o();try{await xr.updateTheme(s==="light"?"dark":"light")}catch(j){console.error("Error saving theme:",j)}},A=async j=>{l(j);try{await xr.updatePreferences({thumbnailHeight:j})}catch(W){console.error("Error saving preferences:",W)}},le=async()=>{if(!(!e||d)){g(!0);try{await li.sync(e)}catch(j){console.error("Error refreshing:",j),alert("刷新失败: "+j.message)}finally{g(!1)}}},B=oe.formats,N=oe.sizes.map(j=>({label:j})),V=[{value:"horizontal",label:"横图"},{value:"vertical",label:"竖图"}].filter(j=>j.value==="horizontal"&&oe.hasHorizontal||j.value==="vertical"&&oe.hasVertical);if(S){const j=h!=="sidebar";return k.jsxs("header",{className:"border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800",children:[k.jsxs("div",{className:"h-14 flex items-center justify-between px-4",children:[k.jsx("h1",{className:"text-lg font-bold text-gray-900 dark:text-white",children:"FlyPic"}),k.jsxs("div",{className:"flex items-center gap-2",children:[k.jsx("button",{onClick:le,disabled:!e||d,className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50",children:k.jsx(ed,{className:`w-5 h-5 text-gray-700 dark:text-gray-300 ${d?"animate-spin":""}`})}),k.jsx("button",{onClick:()=>z(!R),className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors",children:k.jsx(td,{className:"w-5 h-5 text-gray-700 dark:text-gray-300"})}),k.jsx("button",{onClick:M,className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors",children:s==="light"?k.jsx(Jc,{className:"w-5 h-5 text-gray-700 dark:text-gray-300"}):k.jsx(rd,{className:"w-5 h-5 text-gray-700 dark:text-gray-300"})})]})]}),j&&k.jsx("div",{className:"px-4 pb-3",children:k.jsxs("div",{className:"flex items-center gap-2",children:[k.jsxs("div",{className:"flex-1 relative",children:[k.jsx(bl,{className:"absolute left-3 top-2.5 w-5 h-5 text-gray-400"}),k.jsx("input",{type:"text",placeholder:"搜索图片...",value:t,onChange:W=>re(W.target.value),className:"w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm"})]}),k.jsx("button",{onClick:()=>y(!w),className:`p-2 border rounded-lg ${v.length>0||x.length>0||_?"border-blue-500 bg-blue-50 dark:bg-blue-500/20":"border-gray-300 dark:border-gray-600"}`,children:k.jsx(Gc,{className:`w-5 h-5 ${v.length>0||x.length>0||_?"text-blue-600 dark:text-blue-300":"text-gray-600 dark:text-gray-400"}`})})]})}),R&&k.jsx("div",{className:"px-4 pb-3 border-t border-gray-200 dark:border-gray-700 pt-3",children:k.jsxs("div",{className:"flex flex-col gap-3",children:[k.jsxs("div",{className:"flex items-center justify-between",children:[k.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300",children:"缩略图大小"}),k.jsxs("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:[a,"px"]})]}),k.jsx("input",{type:"range",min:"150",max:"300",value:a,onChange:W=>A(parseInt(W.target.value)),className:"w-full h-2 bg-gray-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer",style:{background:`linear-gradient(to right, #3b82f6 0%, #3b82f6 ${(a-150)/150*100}%, #e5e7eb ${(a-150)/150*100}%, #e5e7eb 100%)`}})]})}),j&&w&&k.jsxs("div",{className:"px-4 pb-3 border-t border-gray-200 dark:border-gray-700 pt-3",children:[k.jsxs("div",{className:"flex items-center justify-between mb-3",children:[k.jsx("span",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"筛选条件"}),k.jsx("button",{onClick:J,className:"text-xs text-blue-500",children:"清除全部"})]}),k.jsxs("div",{className:"mb-3",children:[k.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-2",children:"格式"}),k.jsx("div",{className:"flex flex-wrap gap-2",children:B.map(W=>k.jsx("button",{onClick:()=>Q(W),className:`px-3 py-1 text-xs rounded-full ${v.includes(W)?"bg-blue-500 text-white":"bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300"}`,children:W.toUpperCase()},W))})]}),k.jsxs("div",{className:"mb-3",children:[k.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-2",children:"尺寸"}),k.jsx("div",{className:"flex flex-wrap gap-2",children:N.map(W=>k.jsx("button",{onClick:()=>Y(W.label),className:`px-3 py-1 text-xs rounded-full ${x.includes(W.label)?"bg-blue-500 text-white":"bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300"}`,children:W.label},W.label))})]}),k.jsxs("div",{children:[k.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-2",children:"方向"}),k.jsx("div",{className:"flex flex-wrap gap-2",children:V.map(W=>k.jsx("button",{onClick:()=>$(W.value),className:`px-3 py-1 text-xs rounded-full ${_===W.value?"bg-blue-500 text-white":"bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300"}`,children:W.label},W.value))})]})]})]})}return k.jsxs("header",{className:"border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800",children:[k.jsxs("div",{className:"h-14 flex items-center justify-between px-6",children:[k.jsxs("div",{className:"flex-shrink-0",children:[k.jsx("h1",{className:"text-xl font-bold text-gray-900 dark:text-white",children:"FlyPic"}),k.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"轻量快速的图片素材库管理"})]}),k.jsxs("div",{className:"flex-1 max-w-2xl mx-6 flex items-center gap-3",children:[k.jsxs("div",{className:"flex-1 relative",children:[k.jsx(bl,{className:"absolute left-3 top-2.5 w-5 h-5 text-gray-400"}),k.jsx("input",{type:"text",placeholder:"搜索图片... (多个关键词用空格分隔,即时搜索)",value:O,onChange:j=>re(j.target.value),className:"w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),k.jsxs("button",{onClick:()=>y(!w),className:`relative p-2 border rounded-lg transition-colors ${v.length>0||x.length>0||_?"border-blue-500 dark:border-blue-400 bg-blue-50 dark:bg-blue-500/20 hover:bg-blue-100 dark:hover:bg-blue-500/30":"border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700"}`,title:v.length>0||x.length>0||_?"筛选(已启用)":"筛选",children:[k.jsx(Gc,{className:`w-5 h-5 ${v.length>0||x.length>0||_?"text-blue-600 dark:text-blue-300":"text-gray-600 dark:text-gray-400"}`}),(v.length>0||x.length>0||_)&&k.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full",style:{backgroundColor:"#3b82f6"}})]})]}),k.jsxs("div",{className:"flex items-center gap-3 flex-shrink-0",children:[k.jsx(td,{className:"w-4 h-4 text-gray-500"}),k.jsx("input",{type:"range",min:"150",max:"300",value:a,onChange:j=>A(parseInt(j.target.value)),className:"w-32"}),k.jsxs("span",{className:"text-sm text-gray-600 dark:text-gray-400 w-12",children:[a,"px"]}),k.jsx("button",{onClick:le,disabled:!e||d,className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed ml-2",title:"手动刷新素材库(文件监控已自动启用)",children:k.jsx(ed,{className:`w-5 h-5 text-gray-700 dark:text-gray-300 ${d?"animate-spin":""}`})}),k.jsx("button",{onClick:M,className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors",title:s==="light"?"切换到暗色模式":"切换到亮色模式",children:s==="light"?k.jsx(Jc,{className:"w-5 h-5 text-gray-700 dark:text-gray-300"}):k.jsx(rd,{className:"w-5 h-5 text-gray-700 dark:text-gray-300"})})]})]}),w&&k.jsx("div",{className:"px-6 pb-3",children:k.jsxs("div",{className:"p-4 bg-gray-50 dark:bg-gray-700 rounded-lg",children:[k.jsxs("div",{className:"flex items-center justify-between mb-3",children:[k.jsx("div",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"筛选条件(实时生效)"}),k.jsx("button",{onClick:J,className:"text-xs text-blue-500 hover:text-blue-600 dark:hover:text-blue-400",children:"清除全部"})]}),k.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[k.jsxs("div",{children:[k.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-2",children:"格式"}),k.jsx("div",{className:"flex flex-col gap-1.5",children:oe.formats.length>0?oe.formats.map(j=>k.jsx("button",{onClick:()=>Q(j),className:`px-3 py-1.5 text-xs rounded transition-colors text-left ${v.includes(j)?"bg-blue-500 text-white":"bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500"}`,children:j.toUpperCase()},j)):k.jsx("span",{className:"text-xs text-gray-400 py-2",children:"暂无格式数据"})})]}),k.jsxs("div",{children:[k.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-2",children:"文件大小"}),k.jsx("div",{className:"flex flex-col gap-1.5",children:oe.sizes.length>0?oe.sizes.map(j=>k.jsx("button",{onClick:()=>Y(j),className:`px-3 py-1.5 text-xs rounded transition-colors text-left ${x.includes(j)?"bg-blue-500 text-white":"bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500"}`,children:j},j)):k.jsx("span",{className:"text-xs text-gray-400 py-2",children:"暂无大小数据"})})]}),k.jsxs("div",{children:[k.jsx("label",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-2",children:"图片方向"}),k.jsxs("div",{className:"flex flex-col gap-1.5",children:[oe.hasHorizontal&&k.jsx("button",{onClick:()=>$("horizontal"),className:`px-3 py-1.5 text-xs rounded transition-colors text-left ${_==="horizontal"?"bg-blue-500 text-white":"bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500"}`,children:"横图"}),oe.hasVertical&&k.jsx("button",{onClick:()=>$("vertical"),className:`px-3 py-1.5 text-xs rounded transition-colors text-left ${_==="vertical"?"bg-blue-500 text-white":"bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500"}`,children:"竖图"}),!oe.hasHorizontal&&!oe.hasVertical&&k.jsx("span",{className:"text-xs text-gray-400 py-2",children:"暂无方向数据"})]})]})]})]})})]})}function zv(){const{theme:e,mobileView:t,setMobileView:r}=yt(),{setLibraries:n,setCurrentLibrary:i}=rr(),{selectedImage:s}=_e(),{setScanProgress:o}=cn(),[a,l]=G.useState(256),[h,w]=G.useState(320),[y,v]=G.useState(!1),[p,x]=G.useState(!1),[u,_]=G.useState(!1),c=G.useRef(null);G.useEffect(()=>{e==="dark"?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark")},[e]),G.useEffect(()=>{const S=()=>{const b=window.innerWidth<768;_(b)};return S(),window.addEventListener("resize",S),()=>window.removeEventListener("resize",S)},[]),G.useEffect(()=>{u&&s&&r("detail")},[s,u,r]),G.useEffect(()=>{const S=window.location.origin,b=Ys(S,{transports:["websocket","polling"],reconnection:!0,reconnectionDelay:1e3,reconnectionAttempts:5});return b.on("connect",()=>{const R=(z=5,O=1e3)=>{const I=rr.getState().currentLibraryId;I&&li.getStatus(I).then(P=>{const re=P.data||P;re&&re.status==="scanning"&&re.progress?o(re.progress):z>0&&setTimeout(()=>R(z-1,O),O)}).catch(P=>{z>0&&setTimeout(()=>R(z-1,O),O)})};R(5,1e3)}),b.on("connect_error",R=>{console.error("❌ 连接错误:",R.message)}),b.on("scanProgress",R=>{const z=rr.getState().currentLibraryId;R.libraryId===z&&o(R)}),b.on("scanComplete",({libraryId:R,results:z})=>{const O=rr.getState().currentLibraryId;if(R===O){const I=_e.getState(),P={keywords:I.searchKeywords,...I.filters};I.selectedFolder&&(P.folder=I.selectedFolder),Promise.all([Le.getFolders(R),I.selectedFolder||I.searchKeywords||I.filters.formats.length>0?Le.search(R,P):Promise.resolve({images:[]}),Le.getCount(R)]).then(([re,T,H])=>{_e.getState().setFolders(re.folders),_e.getState().setImages(T.images),_e.getState().setTotalImageCount(H.count)}).catch(re=>{console.error("❌ 加载数据失败:",re.message)}).finally(()=>{o(null)})}else o(null)}),b.on("scanError",({libraryId:R,error:z})=>{o(null),console.error("❌ 扫描错误:",z)}),d(),()=>{b.disconnect(),Sl.cleanup()}},[]);const d=async()=>{try{const S=await xr.getAll(),b=S.data||S;n(b.libraries||[]),i(b.currentLibraryId);const R=b.currentLibraryId;if(b.theme&&yt.getState().setTheme(b.theme),b.preferences){const{thumbnailHeight:z,leftPanelWidth:O,rightPanelWidth:I}=b.preferences;z&&yt.getState().setThumbnailHeight(z),O&&l(O),I&&w(I)}if(R){const[z]=await Promise.all([Le.getFolders(R)]);_e.getState().setFolders(z.folders);try{const O=await Le.getCount(R);_e.getState().setTotalImageCount(O.count)}catch(O){console.error("❌ 获取图片总数失败:",O.message)}li.getStatus(R).then(O=>{const{status:I,progress:P}=O;I==="scanning"&&o(P)}).catch(()=>{})}}catch(S){console.error("❌ 加载素材库失败:",S.message)}},g=async(S,b)=>{try{await xr.updatePreferences({leftPanelWidth:S,rightPanelWidth:b})}catch(R){console.error("❌ 保存面板宽度失败:",R.message)}};return G.useEffect(()=>{if(!y&&!p)return;const S=document.getElementById("left-panel"),b=document.getElementById("right-panel");let R=a,z=h;const O=c.current.getBoundingClientRect(),I=O.left,P=O.right;let re=null,T=null,H=null;const m=()=>{S&&T!=null&&(S.style.width=`${T}px`,R=T),b&&H!=null&&(b.style.width=`${H}px`,z=H),re=null,T=null,H=null},K=Q=>{let Y=!1;if(y&&S){const $=Q.clientX-I;$>=200&&$<=400&&(T=$,Y=!0)}if(p&&b){const $=P-Q.clientX;$>=280&&$<=500&&(H=$,Y=!0)}Y&&re==null&&(re=requestAnimationFrame(m))},oe=()=>{re&&(cancelAnimationFrame(re),m()),l(R),w(z),g(R,z),v(!1),x(!1),yt.getState().setIsResizingPanels(!1),yt.getState().setResizingSide(null)};return document.addEventListener("mousemove",K,{passive:!0}),document.addEventListener("mouseup",oe),document.body.style.userSelect="none",document.body.style.cursor="col-resize",S&&(S.style.transition="none"),b&&(b.style.transition="none"),()=>{re&&(cancelAnimationFrame(re),re=null),document.removeEventListener("mousemove",K),document.removeEventListener("mouseup",oe),document.body.style.userSelect="",document.body.style.cursor="",S&&(S.style.transition=""),b&&(b.style.transition="")}},[y,p]),u?k.jsxs("div",{className:"flex flex-col h-screen bg-gray-50 dark:bg-gray-900",children:[k.jsx(xd,{}),k.jsxs("div",{className:"flex-1 overflow-hidden relative",children:[k.jsx("div",{className:`absolute inset-0 transition-transform duration-300 ${t==="sidebar"?"translate-x-0":"-translate-x-full"}`,children:k.jsx(id,{})}),k.jsx("div",{className:`absolute inset-0 transition-transform duration-300 ${t==="main"?"translate-x-0":t==="sidebar"?"translate-x-full":"-translate-x-full"}`,children:k.jsx(yd,{})}),k.jsx("div",{className:`absolute inset-0 transition-transform duration-300 ${t==="detail"?"translate-x-0":"translate-x-full"}`,children:k.jsx(wd,{})})]}),k.jsxs("div",{className:"flex border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800",children:[k.jsxs("button",{onClick:()=>r("sidebar"),className:`flex-1 flex flex-col items-center py-2 ${t==="sidebar"?"text-blue-500":"text-gray-500"}`,children:[k.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:k.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"})}),k.jsx("span",{className:"text-xs mt-1",children:"文件夹"})]}),k.jsxs("button",{onClick:()=>r("main"),className:`flex-1 flex flex-col items-center py-2 ${t==="main"?"text-blue-500":"text-gray-500"}`,children:[k.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:k.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})}),k.jsx("span",{className:"text-xs mt-1",children:"图片"})]}),k.jsxs("button",{onClick:()=>r("detail"),disabled:!s,className:`flex-1 flex flex-col items-center py-2 ${t==="detail"?"text-blue-500":"text-gray-500"} disabled:opacity-30`,children:[k.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:k.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),k.jsx("span",{className:"text-xs mt-1",children:"详情"})]})]})]}):k.jsxs("div",{className:"flex flex-col h-screen bg-gray-50 dark:bg-gray-900",children:[k.jsx(xd,{}),k.jsxs("div",{ref:c,className:"flex flex-1 overflow-hidden",children:[k.jsx("div",{id:"left-panel",style:{width:`${a}px`},className:"flex-shrink-0 h-full",children:k.jsx(id,{})}),k.jsx("div",{className:`group relative w-1 h-full cursor-col-resize flex-shrink-0 transition-colors ${y?"bg-blue-500":"bg-gray-200 dark:bg-gray-700 hover:bg-blue-400"}`,onMouseDown:S=>{S.preventDefault(),yt.getState().setIsResizingPanels(!0),yt.getState().setResizingSide("left"),v(!0)},children:k.jsx("div",{className:"absolute inset-y-0 -left-2 -right-2 w-5"})}),k.jsx("div",{className:"flex-1 min-w-0 h-full",children:k.jsx(yd,{})}),k.jsx("div",{className:`group relative w-1 h-full cursor-col-resize flex-shrink-0 transition-colors ${p?"bg-blue-500":"bg-gray-200 dark:bg-gray-700 hover:bg-blue-400"}`,onMouseDown:S=>{S.preventDefault(),yt.getState().setIsResizingPanels(!0),yt.getState().setResizingSide("right"),x(!0)},children:k.jsx("div",{className:"absolute inset-y-0 -left-2 -right-2 w-5"})}),k.jsx("div",{id:"right-panel",style:{width:`${h}px`},className:"flex-shrink-0 h-full",children:k.jsx(wd,{})})]})]})}ba.createRoot(document.getElementById("root")).render(k.jsx(ye.StrictMode,{children:k.jsx(zv,{})})); diff --git a/flypic/app/server/public/assets/index-lXh_CTLb.css b/flypic/app/server/public/assets/index-lXh_CTLb.css deleted file mode 100644 index 4b9494f..0000000 --- a/flypic/app/server/public/assets/index-lXh_CTLb.css +++ /dev/null @@ -1 +0,0 @@ -.PhotoView-Portal{direction:ltr;height:100%;left:0;overflow:hidden;position:fixed;top:0;touch-action:none;width:100%;z-index:2000}@keyframes PhotoView__rotate{0%{transform:rotate(0)}to{transform:rotate(1turn)}}@keyframes PhotoView__delayIn{0%,50%{opacity:0}to{opacity:1}}.PhotoView__Spinner{animation:PhotoView__delayIn .4s linear both}.PhotoView__Spinner svg{animation:PhotoView__rotate .6s linear infinite}.PhotoView__Photo{cursor:grab;max-width:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.PhotoView__Photo:active{cursor:grabbing}.PhotoView__icon{display:inline-block;left:0;position:absolute;top:0;transform:translate(-50%,-50%)}.PhotoView__PhotoBox,.PhotoView__PhotoWrap{bottom:0;direction:ltr;left:0;position:absolute;right:0;top:0;touch-action:none;width:100%}.PhotoView__PhotoWrap{overflow:hidden;z-index:10}.PhotoView__PhotoBox{transform-origin:left top}@keyframes PhotoView__fade{0%{opacity:0}to{opacity:1}}.PhotoView-Slider__clean .PhotoView-Slider__ArrowLeft,.PhotoView-Slider__clean .PhotoView-Slider__ArrowRight,.PhotoView-Slider__clean .PhotoView-Slider__BannerWrap,.PhotoView-Slider__clean .PhotoView-Slider__Overlay,.PhotoView-Slider__willClose .PhotoView-Slider__BannerWrap:hover{opacity:0}.PhotoView-Slider__Backdrop{background:#000;height:100%;left:0;position:absolute;top:0;transition-property:background-color;width:100%;z-index:-1}.PhotoView-Slider__fadeIn{animation:PhotoView__fade linear both;opacity:0}.PhotoView-Slider__fadeOut{animation:PhotoView__fade linear reverse both;opacity:0}.PhotoView-Slider__BannerWrap{align-items:center;background-color:#00000080;color:#fff;display:flex;height:44px;justify-content:space-between;left:0;position:absolute;top:0;transition:opacity .2s ease-out;width:100%;z-index:20}.PhotoView-Slider__BannerWrap:hover{opacity:1}.PhotoView-Slider__Counter{font-size:14px;opacity:.75;padding:0 10px}.PhotoView-Slider__BannerRight{align-items:center;display:flex;height:100%}.PhotoView-Slider__toolbarIcon{fill:#fff;box-sizing:border-box;cursor:pointer;opacity:.75;padding:10px;transition:opacity .2s linear}.PhotoView-Slider__toolbarIcon:hover{opacity:1}.PhotoView-Slider__ArrowLeft,.PhotoView-Slider__ArrowRight{align-items:center;bottom:0;cursor:pointer;display:flex;height:100px;justify-content:center;margin:auto;opacity:.75;position:absolute;top:0;transition:opacity .2s linear;-webkit-user-select:none;-moz-user-select:none;user-select:none;width:70px;z-index:20}.PhotoView-Slider__ArrowLeft:hover,.PhotoView-Slider__ArrowRight:hover{opacity:1}.PhotoView-Slider__ArrowLeft svg,.PhotoView-Slider__ArrowRight svg{fill:#fff;background:#0000004d;box-sizing:content-box;height:24px;padding:10px;width:24px}.PhotoView-Slider__ArrowLeft{left:0}.PhotoView-Slider__ArrowRight{right:0}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.container{width:100%}@media (min-width: 640px){.container{max-width:640px}}@media (min-width: 768px){.container{max-width:768px}}@media (min-width: 1024px){.container{max-width:1024px}}@media (min-width: 1280px){.container{max-width:1280px}}@media (min-width: 1536px){.container{max-width:1536px}}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.inset-y-0{top:0;bottom:0}.-bottom-0\.5{bottom:-.125rem}.-left-2{left:-.5rem}.-right-0\.5{right:-.125rem}.-right-2{right:-.5rem}.left-0{left:0}.left-2{left:.5rem}.left-3{left:.75rem}.right-0{right:0}.right-2{right:.5rem}.top-0{top:0}.top-2{top:.5rem}.top-2\.5{top:.625rem}.-z-10{z-index:-10}.z-10{z-index:10}.z-50{z-index:50}.mx-6{margin-left:1.5rem;margin-right:1.5rem}.mx-auto{margin-left:auto;margin-right:auto}.my-2{margin-top:.5rem;margin-bottom:.5rem}.mb-1{margin-bottom:.25rem}.mb-12{margin-bottom:3rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-8{margin-bottom:2rem}.ml-2{margin-left:.5rem}.mr-1{margin-right:.25rem}.mr-2{margin-right:.5rem}.mt-1{margin-top:.25rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.block{display:block}.flex{display:flex}.grid{display:grid}.aspect-square{aspect-ratio:1 / 1}.h-1\.5{height:.375rem}.h-12{height:3rem}.h-14{height:3.5rem}.h-16{height:4rem}.h-2{height:.5rem}.h-3{height:.75rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-8{height:2rem}.h-full{height:100%}.h-px{height:1px}.h-screen{height:100vh}.max-h-full{max-height:100%}.min-h-0{min-height:0px}.w-1{width:.25rem}.w-12{width:3rem}.w-3{width:.75rem}.w-32{width:8rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-64{width:16rem}.w-8{width:2rem}.w-80{width:20rem}.w-96{width:24rem}.w-full{width:100%}.min-w-0{min-width:0px}.max-w-2xl{max-width:42rem}.max-w-4xl{max-width:56rem}.max-w-full{max-width:100%}.max-w-md{max-width:28rem}.max-w-sm{max-width:24rem}.flex-1{flex:1 1 0%}.flex-shrink-0{flex-shrink:0}.-translate-x-full{--tw-translate-x: -100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-0{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-full{--tw-translate-x: 100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-col-resize{cursor:col-resize}.cursor-pointer{cursor:pointer}.resize{resize:both}.appearance-none{-webkit-appearance:none;-moz-appearance:none;appearance:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-8>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(2rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(2rem * var(--tw-space-y-reverse))}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-blue-200{--tw-border-opacity: 1;border-color:rgb(191 219 254 / var(--tw-border-opacity, 1))}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-gray-100{--tw-border-opacity: 1;border-color:rgb(243 244 246 / var(--tw-border-opacity, 1))}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-red-300{--tw-border-opacity: 1;border-color:rgb(252 165 165 / var(--tw-border-opacity, 1))}.border-yellow-200{--tw-border-opacity: 1;border-color:rgb(254 240 138 / var(--tw-border-opacity, 1))}.border-t-transparent{border-top-color:transparent}.bg-black{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-blue-200{--tw-bg-opacity: 1;background-color:rgb(191 219 254 / var(--tw-bg-opacity, 1))}.bg-blue-50{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.bg-gray-300{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-gray-500{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity, 1))}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-indigo-100{--tw-bg-opacity: 1;background-color:rgb(224 231 255 / var(--tw-bg-opacity, 1))}.bg-pink-500{--tw-bg-opacity: 1;background-color:rgb(236 72 153 / var(--tw-bg-opacity, 1))}.bg-purple-100{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.bg-purple-300{--tw-bg-opacity: 1;background-color:rgb(216 180 254 / var(--tw-bg-opacity, 1))}.bg-purple-500{--tw-bg-opacity: 1;background-color:rgb(168 85 247 / var(--tw-bg-opacity, 1))}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-yellow-200{--tw-bg-opacity: 1;background-color:rgb(254 240 138 / var(--tw-bg-opacity, 1))}.bg-yellow-50{--tw-bg-opacity: 1;background-color:rgb(254 252 232 / var(--tw-bg-opacity, 1))}.bg-yellow-500{--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity, 1))}.bg-opacity-0{--tw-bg-opacity: 0}.bg-opacity-50{--tw-bg-opacity: .5}.bg-opacity-90{--tw-bg-opacity: .9}.fill-white{fill:#fff}.object-contain{-o-object-fit:contain;object-fit:contain}.object-cover{-o-object-fit:cover;object-fit:cover}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-2{padding:.5rem}.p-20{padding:5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pb-3{padding-bottom:.75rem}.pl-10{padding-left:2.5rem}.pl-8{padding-left:2rem}.pr-3{padding-right:.75rem}.pr-4{padding-right:1rem}.pt-3{padding-top:.75rem}.text-left{text-align:left}.text-center{text-align:center}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-6xl{font-size:3.75rem;line-height:1}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-blue-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-indigo-600{--tw-text-opacity: 1;color:rgb(79 70 229 / var(--tw-text-opacity, 1))}.text-purple-600{--tw-text-opacity: 1;color:rgb(147 51 234 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-500{--tw-text-opacity: 1;color:rgb(234 179 8 / var(--tw-text-opacity, 1))}.text-yellow-600{--tw-text-opacity: 1;color:rgb(202 138 4 / var(--tw-text-opacity, 1))}.text-yellow-700{--tw-text-opacity: 1;color:rgb(161 98 7 / var(--tw-text-opacity, 1))}.opacity-100{opacity:1}.opacity-70{opacity:.7}.opacity-75{opacity:.75}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-shadow{transition-property:box-shadow;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-300{transition-duration:.3s}*{margin:0;padding:0;box-sizing:border-box}body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}#root{width:100vw;height:100vh;overflow:hidden}.dark{--tw-bg-opacity: 1}.dark .bg-gray-900{background-color:#0a0a0a!important}.dark .bg-gray-800{background-color:#252525!important}.dark .bg-gray-700{background-color:#2a2a2a!important}.dark .bg-gray-600,.dark .bg-gray-500{background-color:#3a3a3a!important}.dark .bg-gray-400{background-color:#4a4a4a!important}.dark .bg-gray-300{background-color:#2a2a2a!important}.dark .bg-gray-200:not(img):not(.image-container){background-color:#2a2a2a!important}.dark .bg-gray-100,.dark .bg-gray-50,.dark .bg-white{background-color:#1a1a1a!important}.dark .border-gray-700{border-color:#333!important}.dark .border-gray-600{border-color:#444!important}.dark .border-gray-300{border-color:#333!important}.dark .border-gray-200,.dark .border-gray-100{border-color:#2a2a2a!important}.dark .text-gray-900{color:#f5f5f5!important}.dark .text-gray-700{color:#e0e0e0!important}.dark .text-gray-600{color:#b0b0b0!important}.dark .text-gray-500{color:#909090!important}.dark .text-gray-400{color:#707070!important}.dark .text-gray-300{color:#d0d0d0!important}.dark .text-white{color:#fff!important}.dark .text-gray-800{color:#e0e0e0!important}.dark .text-gray-200{color:#d0d0d0!important}.dark .text-gray-100{color:#e0e0e0!important}.dark .bg-opacity-0{--tw-bg-opacity: 0 !important}.dark .bg-opacity-10{--tw-bg-opacity: .1 !important}.dark .bg-opacity-20{--tw-bg-opacity: .2 !important}.dark .bg-opacity-30{--tw-bg-opacity: .3 !important}.dark .bg-opacity-50{--tw-bg-opacity: .5 !important}.dark .hover\:bg-gray-100:hover{background-color:#2a2a2a!important}.dark .hover\:bg-gray-700:hover{background-color:#333!important}.dark .hover\:bg-gray-600:hover{background-color:#3a3a3a!important}.dark .hover\:bg-gray-200:hover,.dark .hover\:bg-gray-50:hover{background-color:#2a2a2a!important}.dark .bg-black:not(.bg-opacity-0):not(.bg-opacity-10):not(.bg-opacity-20):not(.bg-opacity-30){background-color:#0a0a0a!important}.dark .text-black{color:#fff!important}.dark .border-black{border-color:#2a2a2a!important}.dark .bg-blue-50,.dark .bg-blue-100{background-color:#2a2a2a!important}.dark .bg-blue-200{background-color:#3a3a3a!important}.dark .bg-blue-600{background-color:#3a3a3a!important}.dark .bg-blue-800{background-color:#2a2a2a!important}.dark .bg-blue-900{background-color:#1a1a1a!important}.dark .text-blue-300{color:#d0d0d0!important}.dark .text-blue-400{color:#e0e0e0!important}.dark .text-blue-500,.dark .text-blue-600{color:#f0f0f0!important}.dark .text-blue-700{color:#e0e0e0!important}.dark .border-blue-200{border-color:#2a2a2a!important}.dark .border-blue-500{border-color:#4a4a4a!important}.dark .border-blue-700{border-color:#333!important}.dark .hover\:bg-blue-600:hover{background-color:#4a4a4a!important}.dark .hover\:bg-blue-50:hover{background-color:#333!important}.dark .bg-green-50{background-color:#2a2a2a!important}.dark .text-green-600{color:#e0e0e0!important}.dark .bg-red-50{background-color:#2a2a2a!important}.dark .text-red-600{color:#f0a0a0!important}.dark .bg-yellow-50{background-color:#2a2a2a!important}.dark .text-yellow-600{color:#e0e0a0!important}.dark img{background-color:transparent!important}.dark input,.dark select,.dark textarea{background-color:#1a1a1a!important;border-color:#333!important;color:#e0e0e0!important}.dark input:focus,.dark select:focus,.dark textarea:focus{border-color:#4a4a4a!important;outline:none!important;--tw-ring-color: #4a4a4a !important}.dark input::-moz-placeholder{color:#707070!important}.dark input::placeholder{color:#707070!important}.dark button{color:#e0e0e0!important}.dark .bg-blue-500{background-color:#4a4a4a!important}.dark .hover\:bg-blue-600:hover{background-color:#5a5a5a!important}.dark .shadow-lg{box-shadow:0 10px 15px -3px #00000080,0 4px 6px -2px #0000004d!important}.dark .shadow-xl{box-shadow:0 20px 25px -5px #00000080,0 10px 10px -5px #0000004d!important}.dark .hover\:shadow-lg:hover{box-shadow:0 10px 15px -3px #00000080,0 4px 6px -2px #0000004d!important}.dark .ring-blue-500{--tw-ring-color: #4a4a4a !important}.dark .focus\:ring-blue-500:focus{--tw-ring-color: #4a4a4a !important}.dark .focus\:ring-2:focus{--tw-ring-offset-shadow: 0 0 0 0px #000 !important;--tw-ring-shadow: 0 0 0 2px #4a4a4a !important}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:#0003;border-radius:4px}::-webkit-scrollbar-thumb:hover{background:#0000004d}.dark ::-webkit-scrollbar-track{background:#ffffff0d}.dark ::-webkit-scrollbar-thumb{background:#fff3;border-radius:4px}.dark ::-webkit-scrollbar-thumb:hover{background:#ffffff4d}.hover\:bg-blue-100:hover{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-400:hover{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-600:hover{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-300:hover{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.hover\:bg-green-600:hover{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.hover\:bg-purple-600:hover{--tw-bg-opacity: 1;background-color:rgb(147 51 234 / var(--tw-bg-opacity, 1))}.hover\:bg-red-50:hover{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.hover\:bg-white:hover{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.hover\:bg-yellow-600:hover{--tw-bg-opacity: 1;background-color:rgb(202 138 4 / var(--tw-bg-opacity, 1))}.hover\:bg-opacity-20:hover{--tw-bg-opacity: .2}.hover\:text-blue-500:hover{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.hover\:text-blue-600:hover{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.hover\:shadow-lg:hover{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-md:hover{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-blue-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-30:disabled{opacity:.3}.disabled\:opacity-50:disabled{opacity:.5}.group:hover .group-hover\:bg-opacity-20{--tw-bg-opacity: .2}.group:hover .group-hover\:text-yellow-400{--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.dark\:border-blue-400:is(.dark *){--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.dark\:border-blue-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(29 78 216 / var(--tw-border-opacity, 1))}.dark\:border-gray-600:is(.dark *){--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity, 1))}.dark\:border-gray-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.dark\:border-red-600:is(.dark *){--tw-border-opacity: 1;border-color:rgb(220 38 38 / var(--tw-border-opacity, 1))}.dark\:border-yellow-700:is(.dark *){--tw-border-opacity: 1;border-color:rgb(161 98 7 / var(--tw-border-opacity, 1))}.dark\:bg-blue-500\/20:is(.dark *){background-color:#3b82f633}.dark\:bg-blue-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(30 58 138 / var(--tw-bg-opacity, 1))}.dark\:bg-blue-900\/30:is(.dark *){background-color:#1e3a8a4d}.dark\:bg-gray-600:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-700:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.dark\:bg-gray-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.dark\:bg-indigo-900\/30:is(.dark *){background-color:#312e814d}.dark\:bg-purple-900\/30:is(.dark *){background-color:#581c874d}.dark\:bg-yellow-900:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(113 63 18 / var(--tw-bg-opacity, 1))}.dark\:text-blue-300:is(.dark *){--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.dark\:text-blue-400:is(.dark *){--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.dark\:text-gray-100:is(.dark *){--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity, 1))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.dark\:text-gray-500:is(.dark *){--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.dark\:text-gray-600:is(.dark *){--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.dark\:text-indigo-400:is(.dark *){--tw-text-opacity: 1;color:rgb(129 140 248 / var(--tw-text-opacity, 1))}.dark\:text-purple-400:is(.dark *){--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.dark\:text-red-400:is(.dark *){--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.dark\:text-white:is(.dark *){--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.dark\:text-yellow-300:is(.dark *){--tw-text-opacity: 1;color:rgb(253 224 71 / var(--tw-text-opacity, 1))}.dark\:hover\:bg-blue-500\/30:hover:is(.dark *){background-color:#3b82f64d}.dark\:hover\:bg-gray-500:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity, 1))}.dark\:hover\:bg-gray-600:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.dark\:hover\:bg-gray-700:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.dark\:hover\:bg-red-900:hover:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(127 29 29 / var(--tw-bg-opacity, 1))}.dark\:hover\:text-blue-400:hover:is(.dark *){--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}@media (min-width: 768px){.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}@media (min-width: 1024px){.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}} diff --git a/flypic/app/server/public/assets/layoutWorker-D6X91dDa.js b/flypic/app/server/public/assets/layoutWorker-D6X91dDa.js deleted file mode 100644 index c128e29..0000000 --- a/flypic/app/server/public/assets/layoutWorker-D6X91dDa.js +++ /dev/null @@ -1 +0,0 @@ -(function(){"use strict";let c={containerWidth:0,targetHeight:0,imageCount:0,rows:[],pendingRow:[],pendingRowWidthSum:0};function W(n,o,l,i,s){const a=(n.length-1)*16;let e=(o-a)/l;i&&n.length<3&&(e=Math.min(e,1.2));const t=s*e;return n.map(u=>({...u,calculatedWidth:u.originalWidth*e,calculatedHeight:t}))}function A(n,o,l){if(!n.length||!o)return{rows:[],pendingRow:[],pendingRowWidthSum:0};const i=[];let s=[],a=0;for(let h=0;h=o*.95)d=!0;else{const w=n[h+1];if(w){const R=w.width/w.height,G=l*R;a+G+s.length*16>o*1.2&&(d=!0)}}if(d){const w=W(s,o,a,p,l);i.push(w),s=[],a=0}}return{rows:i,pendingRow:s,pendingRowWidthSum:a}}function x(n,o,l,i,s,a){if(!n.length){if(s.length>0){const r=W(s,o,a,!0,l);return{rows:[...i,r],pendingRow:[],pendingRowWidthSum:0}}return{rows:i,pendingRow:[],pendingRowWidthSum:0}}const h=[...i];let e=[...s],t=a;const u=i.reduce((r,g)=>r+g.length,0)+s.length+n.length;for(let r=0;rf+C.length,0)+h.length-i.length+e.length>=u;let m=!1;if(S)m=!0;else if(R>=o*.95)m=!0;else{const f=n[r+1];if(f){const C=f.width/f.height,I=l*C;t+I+e.length*16>o*1.2&&(m=!0)}}if(m){const f=W(e,o,t,S,l);h.push(f),e=[],t=0}}return{rows:h,pendingRow:e,pendingRowWidthSum:t}}function P(){c={containerWidth:0,targetHeight:0,imageCount:0,rows:[],pendingRow:[],pendingRowWidthSum:0}}self.onmessage=function(n){const{images:o,containerWidth:l,targetHeight:i,requestId:s,incremental:a,reset:h}=n.data;if(h){P(),self.postMessage({requestId:s,reset:!0});return}const e=performance.now();let t;const u=a&&c.containerWidth===l&&c.targetHeight===i&&o.length>c.imageCount;if(u){const g=o.slice(c.imageCount),p=c.rows.slice(0,-1),d=c.rows[c.rows.length-1]||[];t=x(g,l,i,p,c.pendingRow.length>0?c.pendingRow:d,c.pendingRowWidthSum>0?c.pendingRowWidthSum:d.reduce((w,R)=>w+R.originalWidth,0))}else t=A(o,l,i);c={containerWidth:l,targetHeight:i,imageCount:o.length,rows:t.rows,pendingRow:t.pendingRow,pendingRowWidthSum:t.pendingRowWidthSum};const r=performance.now()-e;self.postMessage({rows:t.rows,requestId:s,duration:r,imageCount:o.length,rowCount:t.rows.length,incremental:u})}})(); diff --git a/flypic/app/server/public/index.html b/flypic/app/server/public/index.html index 5231c42..4befc22 100644 --- a/flypic/app/server/public/index.html +++ b/flypic/app/server/public/index.html @@ -5,8 +5,8 @@ FlyPic 飞图 - 图片素材库管理 - - + +
diff --git a/flypic/app/server/routes/image.js b/flypic/app/server/routes/image.js deleted file mode 100644 index 77b8e9f..0000000 --- a/flypic/app/server/routes/image.js +++ /dev/null @@ -1,297 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const path = require('path'); -const fs = require('fs'); -const { exec } = require('child_process'); -const dbPool = require('../database/dbPool'); -const { generateThumbnail } = require('../utils/thumbnail'); -const { getLibrary } = require('../utils/config'); - -// Get images with search and filters (supports pagination) -router.get('/', (req, res) => { - try { - const { libraryId, keywords, folder, formats, minSize, maxSize, startDate, endDate, offset, limit } = req.query; - - if (!libraryId) { - return res.status(400).json({ error: 'Library ID is required' }); - } - - const library = getLibrary(libraryId); - if (!library) { - return res.status(404).json({ error: 'Library not found' }); - } - - // 使用连接池获取数据库连接 - const db = dbPool.acquire(library.path); - - try { - const filters = {}; - if (folder) filters.folder = folder; - if (formats) filters.formats = formats.split(','); - if (minSize) filters.minSize = parseInt(minSize); - if (maxSize) filters.maxSize = parseInt(maxSize); - if (startDate) filters.startDate = parseInt(startDate); - if (endDate) filters.endDate = parseInt(endDate); - - // 分页参数(可选) - let pagination = null; - if (offset !== undefined && limit !== undefined) { - pagination = { - offset: parseInt(offset, 10), - limit: parseInt(limit, 10) - }; - } - - const result = db.searchImages(keywords || '', filters, pagination); - - // 如果使用分页,返回分页格式;否则保持向后兼容 - if (pagination) { - res.json({ - images: result.images, - total: result.total, - offset: result.offset, - limit: result.limit, - hasMore: result.hasMore - }); - } else { - res.json({ images: result }); - } - } finally { - // 释放连接 - dbPool.release(library.path); - } - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// Get cache metadata (database modification time, counts) -router.get('/cache-meta', (req, res) => { - try { - const { libraryId } = req.query; - - if (!libraryId) { - return res.status(400).json({ error: 'Library ID is required' }); - } - - const library = getLibrary(libraryId); - if (!library) { - return res.status(404).json({ error: 'Library not found' }); - } - - const db = dbPool.acquire(library.path); - try { - const meta = db.getCacheMeta(); - res.json(meta); - } finally { - dbPool.release(library.path); - } - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// Get total image count -router.get('/count', (req, res) => { - try { - const { libraryId } = req.query; - - if (!libraryId) { - return res.status(400).json({ error: 'Library ID is required' }); - } - - const library = getLibrary(libraryId); - if (!library) { - return res.status(404).json({ error: 'Library not found' }); - } - - const db = dbPool.acquire(library.path); - - try { - const row = db.db.prepare('SELECT COUNT(*) as count FROM images').get(); - res.json({ count: row.count }); - } finally { - dbPool.release(library.path); - } - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// Get folders -router.get('/folders', (req, res) => { - try { - const { libraryId } = req.query; - - if (!libraryId) { - return res.status(400).json({ error: 'Library ID is required' }); - } - - const library = getLibrary(libraryId); - if (!library) { - return res.status(404).json({ error: 'Library not found' }); - } - - const db = dbPool.acquire(library.path); - - try { - const folders = db.getFolderTree(); - res.json({ folders }); - } finally { - dbPool.release(library.path); - } - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// Serve thumbnail -router.get('/thumbnail/:libraryId/:size/:filename', async (req, res) => { - try { - const { libraryId, size, filename } = req.params; - - const library = getLibrary(libraryId); - if (!library) { - return res.status(404).json({ error: 'Library not found' }); - } - - // New structure: .flypic/thumbnails/ab/hash.webp - const thumbBase = path.join(library.path, '.flypic', 'thumbnails'); - const hash = filename.replace(/\.[^/.]+$/, ""); // remove extension if present - const shard1 = hash.slice(0, 2); - - const targetPath = path.join(thumbBase, shard1, filename); - - if (!fs.existsSync(targetPath)) { - // 按需生成:尝试通过文件名在数据库中定位原图并生成 - try { - const db = dbPool.acquire(library.path); - try { - const row = db.db.prepare('SELECT path, thumbnail_path FROM images WHERE thumbnail_path LIKE ?').get(`%/${filename}`); - if (row && row.path) { - const originalFull = path.join(library.path, row.path); - // 确保目标目录存在 - fs.mkdirSync(path.dirname(targetPath), { recursive: true }); - // 生成指定尺寸 (default 480) - await generateThumbnail(originalFull, targetPath, parseInt(size, 10) || 480); - } - } finally { - dbPool.release(library.path); - } - } catch (e) { - // 忽略生成失败 - } - } - - if (!fs.existsSync(targetPath)) { - return res.status(404).json({ error: 'Thumbnail not found' }); - } - - // 设置缓存头,减少重复请求(缩略图内容不变) - res.set({ - 'Cache-Control': 'public, max-age=31536000, immutable', - 'Vary': 'Accept-Encoding' - }); - res.sendFile(targetPath); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// Serve original image -router.get('/original/:libraryId/*', (req, res) => { - try { - const { libraryId } = req.params; - const imagePath = req.params[0]; - - const library = getLibrary(libraryId); - if (!library) { - return res.status(404).json({ error: 'Library not found' }); - } - - const fullPath = path.join(library.path, imagePath); - - if (!fs.existsSync(fullPath)) { - return res.status(404).json({ error: 'Image not found' }); - } - - res.sendFile(fullPath); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// Open file in system default application -router.post('/:libraryId/open-file', (req, res) => { - try { - const { libraryId } = req.params; - const { path: filePath } = req.body; - - if (!filePath) { - return res.status(400).json({ error: 'Path is required' }); - } - - const library = getLibrary(libraryId); - if (!library) { - return res.status(404).json({ error: 'Library not found' }); - } - - const fullPath = path.join(library.path, filePath); - - if (!fs.existsSync(fullPath)) { - return res.status(404).json({ error: 'File not found' }); - } - - // 使用系统默认应用打开文件 - const command = process.platform === 'win32' - ? `start "" "${fullPath}"` - : process.platform === 'darwin' - ? `open "${fullPath}"` - : `xdg-open "${fullPath}"`; - - exec(command, (error) => { - if (error) { - console.error('打开文件失败:', error); - return res.status(500).json({ error: '打开文件失败' }); - } - res.json({ success: true }); - }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// Open folder in file explorer -router.post('/:libraryId/open-folder', (req, res) => { - try { - const { path: imagePath } = req.body; - - if (!imagePath) { - return res.status(400).json({ error: 'Path is required' }); - } - - // 获取文件所在文件夹 - const folderPath = path.dirname(imagePath); - - // Windows: 使用 explorer - // Linux: 使用 xdg-open - // macOS: 使用 open - const command = process.platform === 'win32' - ? `explorer "${folderPath}"` - : process.platform === 'darwin' - ? `open "${folderPath}"` - : `xdg-open "${folderPath}"`; - - exec(command, (error) => { - if (error) { - console.error('打开文件夹失败:', error); - return res.status(500).json({ error: '打开文件夹失败' }); - } - res.json({ success: true }); - }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -module.exports = router; diff --git a/flypic/app/server/routes/library.js b/flypic/app/server/routes/library.js deleted file mode 100644 index f26e5b8..0000000 --- a/flypic/app/server/routes/library.js +++ /dev/null @@ -1,238 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const fs = require('fs'); -const { - loadConfig, - addLibrary, - removeLibrary, - updateLibrary, - setCurrentLibrary, - updatePreferences, - updateTheme -} = require('../utils/config'); - -// Get all libraries and config -router.get('/', (req, res) => { - try { - const config = loadConfig(); - res.json({ - libraries: config.libraries, - currentLibraryId: config.currentLibraryId, - theme: config.theme, - preferences: config.preferences - }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// Add new library -router.post('/', (req, res) => { - try { - const { name, path } = req.body; - - if (!name || !path) { - return res.status(400).json({ error: 'Name and path are required' }); - } - - if (!fs.existsSync(path)) { - return res.status(400).json({ error: 'Path does not exist' }); - } - - const id = addLibrary(name, path); - - // Check if .flypic directory exists - const flypicDir = require('path').join(path, '.flypic'); - const hasExistingIndex = fs.existsSync(flypicDir); - - res.json({ - id, - message: 'Library added successfully', - hasExistingIndex - }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// Update preferences (must be before /:id route) -router.put('/preferences', (req, res) => { - try { - const preferences = updatePreferences(req.body); - res.json({ preferences }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// Update theme (must be before /:id route) -router.put('/theme', (req, res) => { - try { - const { theme } = req.body; - updateTheme(theme); - res.json({ theme }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// Update library -router.put('/:id', (req, res) => { - try { - const { id } = req.params; - const updates = req.body; - - const success = updateLibrary(id, updates); - if (success) { - res.json({ message: 'Library updated successfully' }); - } else { - res.status(404).json({ error: 'Library not found' }); - } - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// Delete library -router.delete('/:id', async (req, res) => { - try { - const { id } = req.params; - - // 获取素材库信息 - const config = loadConfig(); - const library = config.libraries.find(lib => lib.id === id); - - if (!library) { - return res.status(404).json({ error: 'Library not found' }); - } - - const dbPool = require('../database/dbPool'); - const fileWatcher = require('../utils/fileWatcher'); - const scanManager = require('../utils/scanManager'); - - // 1. 停止扫描并清理状态 - scanManager.clearState(id); - - // 2. 停止文件监控 - fileWatcher.unwatch(id); - - // 3. 关闭数据库连接 - dbPool.close(library.path); - - // 等待一下,确保连接完全关闭 - await new Promise(resolve => setTimeout(resolve, 300)); - - // 删除索引 - removeLibrary(id); - - res.json({ - message: 'Library removed successfully', - path: library.path - }); - } catch (error) { - console.error('Error in delete library:', error); - res.status(500).json({ error: error.message }); - } -}); - -// Set current library -router.post('/:id/set-current', async (req, res) => { - try { - const { id } = req.params; - const config = loadConfig(); - const dbPool = require('../database/dbPool'); - const scanManager = require('../utils/scanManager'); - - // 获取旧的当前素材库 - const oldLibraryId = config.currentLibraryId; - if (oldLibraryId && oldLibraryId !== id) { - const oldLibrary = config.libraries.find(lib => lib.id === oldLibraryId); - if (oldLibrary) { - // 1. 停止扫描(如果正在进行),但保留暂停状态以便恢复 - if (scanManager.isScanning(oldLibraryId)) { - const state = scanManager.getState(oldLibraryId); - if (state.abortController) { - state.abortController.aborted = true; - } - } - - // 2. 关闭数据库连接 - dbPool.close(oldLibrary.path); - } - } - - // 设置新的当前素材库 - setCurrentLibrary(id); - - const newLibrary = config.libraries.find(lib => lib.id === id); - - // 预热新数据库连接(避免第一个查询时才创建连接) - if (newLibrary) { - const db = dbPool.acquire(newLibrary.path); - // 执行一个简单查询来预热缓存 - try { - db.db.prepare('SELECT 1').get(); - } catch (e) { - // 忽略预热错误 - } - dbPool.release(newLibrary.path); - } - - res.json({ message: 'Current library set successfully' }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// Close database connection for a library -router.post('/:id/close-db', (req, res) => { - try { - const { id } = req.params; - const config = loadConfig(); - const library = config.libraries.find(lib => lib.id === id); - - if (!library) { - return res.status(404).json({ error: 'Library not found' }); - } - - const dbPool = require('../database/dbPool'); - dbPool.close(library.path); - - res.json({ message: 'Database connection closed successfully' }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// Release all resources for a library (database + file watcher) -router.post('/:id/release', (req, res) => { - try { - const { id } = req.params; - const config = loadConfig(); - const library = config.libraries.find(lib => lib.id === id); - - if (!library) { - return res.status(404).json({ error: 'Library not found' }); - } - - // 1. 关闭数据库连接 - const dbPool = require('../database/dbPool'); - dbPool.close(library.path); - - // 2. 停止文件监控 - const fileWatcher = req.app.get('fileWatcher'); - if (fileWatcher && fileWatcher.isWatching(id)) { - fileWatcher.unwatch(id); - } - - res.json({ - message: 'All resources released successfully', - library: library.name - }); - } catch (error) { - console.error('[Release] Error:', error); - res.status(500).json({ error: error.message }); - } -}); - -module.exports = router; diff --git a/flypic/app/server/routes/scan.js b/flypic/app/server/routes/scan.js deleted file mode 100644 index abc374d..0000000 --- a/flypic/app/server/routes/scan.js +++ /dev/null @@ -1,283 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const LibraryDatabase = require('../database/db'); -const { getLibrary, updateLibrary } = require('../utils/config'); -const { scanLibrary, syncLibrary } = require('../utils/scanner'); -const scanManager = require('../utils/scanManager'); - -// Start full scan -router.post('/full', async (req, res) => { - try { - const { libraryId, wait } = req.body; - - if (!libraryId) { - return res.status(400).json({ error: 'Library ID is required' }); - } - - const library = getLibrary(libraryId); - if (!library) { - return res.status(404).json({ error: 'Library not found' }); - } - - const io = req.app.get('io'); - const dbPool = require('../database/dbPool'); - const db = dbPool.acquire(library.path); - - // 如果需要等待扫描完成 - if (wait) { - try { - const results = await scanLibrary(library.path, db, (progress) => { - io.emit('scanProgress', { - libraryId, - ...progress - }); - }); - - dbPool.release(library.path); - updateLibrary(libraryId, { lastScan: Date.now() }); - io.emit('scanComplete', { libraryId, results }); - - res.json({ message: 'Scan completed', results }); - } catch (error) { - dbPool.release(library.path); - io.emit('scanError', { libraryId, error: error.message }); - throw error; - } - } else { - // Start scan in background - console.log(`🔍 Starting background scan for library: ${libraryId}`); - res.json({ message: 'Scan started' }); - - scanLibrary(library.path, db, (progress) => { - console.log(`📊 Progress: ${progress.current}/${progress.total} (${progress.percent}%)`); - io.emit('scanProgress', { - libraryId, - ...progress - }); - }, libraryId).then(results => { - console.log(`✅ Scan complete for library: ${libraryId}`, results); - dbPool.release(library.path); - if (!results.stopped) { - updateLibrary(libraryId, { lastScan: Date.now() }); - io.emit('scanComplete', { libraryId, results }); - } else { - io.emit('scanPaused', { libraryId, results }); - } - }).catch(error => { - console.error(`❌ Scan error for library: ${libraryId}`, error); - dbPool.release(library.path); - io.emit('scanError', { libraryId, error: error.message }); - }); - } - - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// Start incremental sync -router.post('/sync', async (req, res) => { - try { - const { libraryId, wait } = req.body; - - if (!libraryId) { - return res.status(400).json({ error: 'Library ID is required' }); - } - - const library = getLibrary(libraryId); - if (!library) { - return res.status(404).json({ error: 'Library not found' }); - } - - const io = req.app.get('io'); - const dbPool = require('../database/dbPool'); - const db = dbPool.acquire(library.path); - - // 如果需要等待同步完成 - if (wait) { - try { - const results = await syncLibrary(library.path, db); - - dbPool.release(library.path); - updateLibrary(libraryId, { lastScan: Date.now() }); - io.emit('scanComplete', { libraryId, results }); - - res.json({ message: 'Sync completed', results }); - } catch (error) { - dbPool.release(library.path); - io.emit('scanError', { libraryId, error: error.message }); - throw error; - } - } else { - // Start sync in background - console.log(`🔄 Starting background sync for library: ${libraryId}`); - res.json({ message: 'Sync started' }); - - syncLibrary(library.path, db, false, (progress) => { - console.log(`📊 Sync progress: ${progress.current}/${progress.total} (${progress.percent}%)`); - io.emit('scanProgress', { - libraryId, - ...progress - }); - }).then(results => { - console.log(`✅ Sync complete for library: ${libraryId}`, results); - dbPool.release(library.path); - updateLibrary(libraryId, { lastScan: Date.now() }); - io.emit('scanComplete', { libraryId, results }); - }).catch(error => { - console.error(`❌ Sync error for library: ${libraryId}`, error); - dbPool.release(library.path); - io.emit('scanError', { libraryId, error: error.message }); - }); - } - - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// Fix folder paths in database (one-time migration) -router.post('/fix-folders', async (req, res) => { - try { - const { libraryId } = req.body; - - if (!libraryId) { - return res.status(400).json({ error: 'Library ID is required' }); - } - - const library = getLibrary(libraryId); - if (!library) { - return res.status(404).json({ error: 'Library not found' }); - } - - const db = dbPool.acquire(library.path); - - try { - const path = require('path'); - const images = db.getAllImages(); - let fixed = 0; - - for (const img of images) { - const expectedFolderRaw = path.dirname(img.path || ''); - const expectedFolder = expectedFolderRaw === '.' ? '' : expectedFolderRaw.replace(/\\/g, '/'); - const currentFolder = (img.folder || '').replace(/\\/g, '/'); - - if (expectedFolder !== currentFolder) { - db.updateImageFolder(img.path, expectedFolder); - fixed++; - } - } - - console.log(`✅ Fixed ${fixed} folder paths`); - res.json({ message: `Fixed ${fixed} folder paths`, fixed }); - } finally { - dbPool.release(library.path); - } - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// 停止扫描 -router.post('/stop', async (req, res) => { - try { - const { libraryId } = req.body; - - if (!libraryId) { - return res.status(400).json({ error: 'Library ID is required' }); - } - - if (!scanManager.isScanning(libraryId)) { - return res.status(400).json({ error: 'No scan in progress' }); - } - - // 设置停止标志(实际停止在下一个批次检查时) - const state = scanManager.getState(libraryId); - state.abortController.aborted = true; - - console.log(`⏸️ Stop requested for library: ${libraryId}`); - res.json({ message: 'Stop requested', libraryId }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// 继续扫描 -router.post('/resume', async (req, res) => { - try { - const { libraryId } = req.body; - - if (!libraryId) { - return res.status(400).json({ error: 'Library ID is required' }); - } - - if (!scanManager.isPaused(libraryId)) { - return res.status(400).json({ error: 'Scan is not paused' }); - } - - const library = getLibrary(libraryId); - if (!library) { - return res.status(404).json({ error: 'Library not found' }); - } - - const pendingFiles = scanManager.resumeScan(libraryId); - if (pendingFiles.length === 0) { - return res.status(400).json({ error: 'No pending files to resume' }); - } - - const io = req.app.get('io'); - const dbPool = require('../database/dbPool'); - const db = dbPool.acquire(library.path); - - console.log(`▶️ Resuming scan for library: ${libraryId}, ${pendingFiles.length} files`); - res.json({ message: 'Scan resumed', pendingFiles: pendingFiles.length }); - - // 继续扫描 - scanLibrary(library.path, db, (progress) => { - io.emit('scanProgress', { - libraryId, - ...progress - }); - }, libraryId, pendingFiles).then(results => { - dbPool.release(library.path); - if (!results.stopped) { - updateLibrary(libraryId, { lastScan: Date.now() }); - io.emit('scanComplete', { libraryId, results }); - } else { - io.emit('scanPaused', { libraryId, results }); - } - }).catch(error => { - dbPool.release(library.path); - io.emit('scanError', { libraryId, error: error.message }); - }); - - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// 获取扫描状态 -router.get('/status/:libraryId', (req, res) => { - try { - const { libraryId } = req.params; - - // 注册素材库路径(用于持久化恢复) - const library = getLibrary(libraryId); - if (library) { - scanManager.registerLibraryPath(libraryId, library.path); - } - - const state = scanManager.getState(libraryId); - res.json({ - libraryId, - status: state.status, - progress: state.progress, - pendingCount: state.pendingFiles?.length || 0, - needsRescan: state.needsRescan || false // 标记是否需要重新扫描 - }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -module.exports = router; diff --git a/flypic/app/server/routes/watch.js b/flypic/app/server/routes/watch.js deleted file mode 100644 index 018cdad..0000000 --- a/flypic/app/server/routes/watch.js +++ /dev/null @@ -1,81 +0,0 @@ -const express = require('express'); -const router = express.Router(); - -// Start watching a library -router.post('/start/:libraryId', (req, res) => { - try { - const { libraryId } = req.params; - const fileWatcher = req.app.get('fileWatcher'); - const io = req.app.get('io'); - - // 立即返回响应,让文件监控在后台启动 - res.json({ - message: 'File watching starting', - libraryId, - isWatching: true - }); - - // 异步启动监控(不阻塞响应) - setImmediate(() => { - try { - fileWatcher.watch(libraryId, io); - } catch (watchError) { - console.error(`Failed to start file watching for ${libraryId}:`, watchError.message); - } - }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// Stop watching a library -router.post('/stop/:libraryId', (req, res) => { - try { - const { libraryId } = req.params; - const fileWatcher = req.app.get('fileWatcher'); - - fileWatcher.unwatch(libraryId); - - res.json({ - message: 'File watching stopped', - libraryId, - isWatching: false - }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// Get watch status -router.get('/status/:libraryId', (req, res) => { - try { - const { libraryId } = req.params; - const fileWatcher = req.app.get('fileWatcher'); - - const isWatching = fileWatcher.isWatching(libraryId); - - res.json({ - libraryId, - isWatching - }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// Get all watched libraries -router.get('/list', (req, res) => { - try { - const fileWatcher = req.app.get('fileWatcher'); - const watchedLibraries = fileWatcher.getWatchedLibraries(); - - res.json({ - watchedLibraries, - count: watchedLibraries.length - }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -module.exports = router; diff --git a/flypic/app/server/server.js b/flypic/app/server/server.js index 11ab316..8e6e1cd 100644 --- a/flypic/app/server/server.js +++ b/flypic/app/server/server.js @@ -1,191 +1,238 @@ -const express = require('express'); -const cors = require('cors'); -const path = require('path'); +/** + * FlyPic 服务器入口(新架构) + * 使用重构后的 Service 层和 Model 层 + */ + const http = require('http'); const { Server } = require('socket.io'); -const fileWatcher = require('./utils/fileWatcher'); +const path = require('path'); +const fs = require('fs'); -const app = express(); -const server = http.createServer(app); -const io = new Server(server, { - cors: { - origin: process.env.FRONTEND_DIST ? false : ['http://localhost:5173', 'http://localhost:3000'], - methods: ['GET', 'POST'] - } -}); +// 导入新架构的应用 +const { createApp } = require('./src/app'); + +// 导入现有的依赖(保持兼容) +const config = require('./utils/config'); +const dbPool = require('./database/dbPool'); +const scanner = require('./utils/scanner'); +const scanManager = require('./utils/scanManager'); +const lightweightWatcher = require('./utils/lightweightWatcher'); +const MemoryMonitor = require('./utils/memoryMonitor'); +const CleanupManager = require('./utils/cleanupManager'); const PORT = process.env.PORT || 15002; -// Auto-detect frontend dist path +// 自动检测前端构建目录 let FRONTEND_DIST = process.env.FRONTEND_DIST; if (!FRONTEND_DIST) { - // Try common locations const possiblePaths = [ - path.join(__dirname, 'public'), // 飞牛 fnOS 打包后的位置 - path.join(__dirname, '../frontend/dist'), // 开发环境 + path.join(__dirname, 'public'), + path.join(__dirname, '../frontend/dist'), path.join(__dirname, '../public'), path.join(__dirname, '../../frontend/dist') ]; for (const p of possiblePaths) { - if (require('fs').existsSync(p)) { + if (fs.existsSync(p)) { FRONTEND_DIST = p; - console.log('✅ Found frontend at:', p); + console.log('✅ 前端目录:', p); break; } } if (!FRONTEND_DIST) { - console.log('⚠️ Frontend not found, tried:', possiblePaths); + console.log('⚠️ 未找到前端,API模式'); } } -// Middleware -app.use(cors()); -app.use(express.json()); - -// API Routes -const libraryRouter = require('./routes/library'); -const imageRouter = require('./routes/image'); -const scanRouter = require('./routes/scan'); -const watchRouter = require('./routes/watch'); -app.use('/api/library', libraryRouter); -app.use('/api/image', imageRouter); -app.use('/api/scan', scanRouter); -app.use('/api/watch', watchRouter); - -// Serve static files (production) +// 设置环境变量 if (FRONTEND_DIST) { - console.log('📁 Serving frontend from:', FRONTEND_DIST); - app.use(express.static(FRONTEND_DIST)); - app.get('*', (req, res) => { - if (!req.path.startsWith('/api')) { - res.sendFile(path.join(FRONTEND_DIST, 'index.html')); - } - }); + process.env.FRONTEND_DIST = FRONTEND_DIST; } -// Socket.IO for real-time updates -io.on('connection', (socket) => { - console.log('Client connected:', socket.id); - - socket.on('disconnect', () => { - console.log('Client disconnected:', socket.id); - }); -}); - -// Make io accessible to routes -app.set('io', io); - -// Make fileWatcher accessible to routes -app.set('fileWatcher', fileWatcher); - -server.listen(PORT, () => { - console.log(`🚀 FlyPic server running on http://localhost:${PORT}`); - - // 只为当前选中的素材库启动文件监控和快速同步 - const { loadConfig } = require('./utils/config'); - const config = loadConfig(); - const currentLibraryId = config.currentLibraryId; - const currentLibrary = config.libraries.find(lib => lib.id === currentLibraryId); - - if (currentLibrary) { - console.log(`📡 启动当前素材库监控: ${currentLibrary.name}`); - - // 启动文件监控 - try { - fileWatcher.watch(currentLibrary.id, io); - console.log(` ✅ 文件监控已启动`); - } catch (err) { - console.log(` ❌ 文件监控失败: ${err.message}`); - } - - // 快速同步检测离线变化 - console.log('🔄 检测离线期间的文件变化...'); - const { quickSync } = require('./utils/scanner'); - const dbPool = require('./database/dbPool'); - - (async () => { - try { - const db = dbPool.acquire(currentLibrary.path); - const results = await quickSync(currentLibrary.path, db); - dbPool.release(currentLibrary.path); - - const changes = results.added + results.deleted; - if (changes > 0) { - console.log(` 📊 ${currentLibrary.name}: +${results.added} -${results.deleted}`); - io.emit('scanComplete', { libraryId: currentLibrary.id, results }); - } else { - console.log(` ✅ ${currentLibrary.name}: 无变化`); - } - } catch (err) { - console.log(` ❌ ${currentLibrary.name}: ${err.message}`); - } - console.log('✅ 启动检查完成'); - })(); - } else { - console.log('📭 未选中素材库,等待用户操作...'); +// 创建 Socket.IO 服务器 +const server = http.createServer(); +const io = new Server(server, { + cors: { + origin: FRONTEND_DIST ? false : ['http://localhost:5173', 'http://localhost:3000'], + methods: ['GET', 'POST'] } }); -// Graceful shutdown - 优雅关闭,释放所有资源 -const gracefulShutdown = (signal) => { - console.log(`\n🛑 Received ${signal}, shutting down gracefully...`); - - try { - // 1. 停止所有文件监控 - console.log('📡 Stopping file watchers...'); - fileWatcher.unwatchAll(); - - // 2. 关闭所有数据库连接 - console.log('💾 Closing database connections...'); - const dbPool = require('./database/dbPool'); - dbPool.closeAll(); - - // 3. 关闭 HTTP 服务器 - console.log('🌐 Closing HTTP server...'); - server.close(() => { - console.log('✅ All resources released, goodbye!'); - process.exit(0); - }); - - // 如果10秒内没有正常关闭,强制退出 - setTimeout(() => { - console.error('⚠️ Forced shutdown after timeout'); - process.exit(1); - }, 10000); - - } catch (error) { - console.error('❌ Error during shutdown:', error); - process.exit(1); - } +// 准备依赖注入 +// 包装 config 函数为对象接口 +const configManager = { + load: () => config.loadConfig(), + save: (data) => config.saveConfig(data), + addLibrary: (name, path) => config.addLibrary(name, path), + removeLibrary: (id) => config.removeLibrary(id), + updateLibrary: (id, updates) => config.updateLibrary(id, updates), + setCurrentLibrary: (id) => config.setCurrentLibrary(id), + updatePreferences: (prefs) => config.updatePreferences(prefs), + updateTheme: (theme) => config.updateTheme(theme) }; -// 监听各种退出信号 -process.on('SIGINT', () => gracefulShutdown('SIGINT')); // Ctrl+C -process.on('SIGTERM', () => gracefulShutdown('SIGTERM')); // kill -process.on('SIGHUP', () => gracefulShutdown('SIGHUP')); // 终端关闭 +const dependencies = { + configManager, + dbPool, + scanner, + scanManager, + lightweightWatcher, + io +}; -// Windows 特殊处理(Ctrl+C) -if (process.platform === 'win32') { - const readline = require('readline'); - const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout +// 创建 Express 应用(使用新架构) +const app = createApp(dependencies); + +// 将 Express 应用挂载到 HTTP 服务器 +server.on('request', app); + +// Socket.IO 连接处理 +io.on('connection', (socket) => { + console.log('✅ 客户端连接:', socket.id); + + socket.on('disconnect', () => { + console.log('❌ 客户端断开:', socket.id); + }); +}); + +// 启动内存监控(开发模式:每30秒输出RSS) +const memoryMonitor = new MemoryMonitor({ + devMode: true, + devLogInterval: 30000 // 30秒 +}); +memoryMonitor.start(); + +// 启动清理管理器 +const cleanupManager = new CleanupManager({ dbPool }); +cleanupManager.startRoutineCleanup(); + +// 启动服务器 +server.listen(PORT, () => { + console.log('\n🚀 FlyPic 服务器已启动'); + console.log(`📡 端口: ${PORT}`); + console.log(`🔌 Socket.IO 就绪`); + if (FRONTEND_DIST) console.log(`📁 前端: ${FRONTEND_DIST}`); + console.log(''); + + try { + const currentConfig = config.loadConfig(); + + // 恢复所有素材库的扫描状态 + if (currentConfig.libraries && currentConfig.libraries.length > 0) { + scanManager.restoreAllStates(currentConfig.libraries); + + // 检查是否有未完成的扫描,自动继续 + const activeStates = scanManager.getAllActiveStates(); + if (Object.keys(activeStates).length > 0) { + console.log(`📊 发现 ${Object.keys(activeStates).length} 个活跃扫描`); + } + + for (const [libraryId, state] of Object.entries(activeStates)) { + const lib = currentConfig.libraries.find(l => l.id === libraryId); + if (lib && state.status === 'scanning') { + console.log(`🔄 恢复扫描: ${lib.name} (${state.progress?.percent || 0}%)`); + + // 立即恢复扫描状态(让前端能检测到) + scanManager.scanStates.set(libraryId, { + status: 'scanning', + progress: state.progress || { current: 0, total: 0, percent: 0 }, + startTime: state.startTime || Date.now() + }); + + // 立即向所有连接的客户端推送扫描状态 + io.emit('scanProgress', { + libraryId, + ...state.progress, + resuming: true + }); + + // 延迟启动实际扫描,等服务完全准备好 + setTimeout(() => { + const db = dbPool.acquire(lib.path); + // 继续扫描(从中断处继续) + scanner.scanLibrary( + lib.path, + db, + (progress) => { + io.emit('scanProgress', { libraryId, ...progress }); + }, + libraryId + ).then(() => { + scanManager.completeScan(libraryId); + io.emit('scanComplete', { libraryId }); + dbPool.release(lib.path); + console.log(`✅ 扫描完成: ${lib.name}`); + }).catch((err) => { + console.error(`❌ 扫描失败: ${lib.name}`, err.message); + scanManager.completeScan(libraryId); + dbPool.release(lib.path); + }); + }, 2000); + } + } + } + + // 为当前素材库启动文件监控 + if (currentConfig.currentLibraryId) { + const currentLib = currentConfig.libraries.find(lib => lib.id === currentConfig.currentLibraryId); + if (currentLib) { + lightweightWatcher.watch(currentLib.id, currentLib.path, currentLib.name, io); + } + } + } catch (e) { + console.warn('⚠️ 初始化失败:', e.message); + } +}); + +// 标记是否正在关闭 +let isShuttingDown = false; + +// 优雅关闭 +const shutdown = async () => { + if (isShuttingDown) return; + isShuttingDown = true; + + console.log('\n🛑 正在关闭服务器...'); + + // 停止接受新连接 + server.close(() => { + console.log('✅ HTTP 服务器已关闭'); }); - rl.on('SIGINT', () => { - process.emit('SIGINT'); - }); -} + // 停止监控 + memoryMonitor.stop(); + cleanupManager.stopRoutineCleanup(); -// 捕获未处理的异常 + // 停止所有文件监控 + lightweightWatcher.stopAll(); + + // 等待扫描任务完成当前批次(最多等2秒) + await new Promise(resolve => setTimeout(resolve, 2000)); + + // 关闭所有数据库连接 + dbPool.closeAll(); + + console.log('✅ 关闭完成'); + process.exit(0); +}; + +// 导出关闭状态供其他模块检查 +module.exports.isShuttingDown = () => isShuttingDown; + +process.on('SIGTERM', shutdown); +process.on('SIGINT', shutdown); + +// 错误处理 process.on('uncaughtException', (error) => { - console.error('❌ Uncaught Exception:', error); - gracefulShutdown('uncaughtException'); + console.error('💥 未捕获异常:', error.message); + shutdown(); }); process.on('unhandledRejection', (reason, promise) => { - console.error('❌ Unhandled Rejection at:', promise, 'reason:', reason); - gracefulShutdown('unhandledRejection'); + console.error('💥 未处理的Promise拒绝:', reason); + shutdown(); }); + +// 导出供测试使用 +module.exports = { app, server, io }; diff --git a/flypic/app/server/src/app.js b/flypic/app/server/src/app.js new file mode 100644 index 0000000..7eb6dd8 --- /dev/null +++ b/flypic/app/server/src/app.js @@ -0,0 +1,95 @@ +/** + * Express 应用配置 + * 使用新的架构:Config → Model → Service → Route + */ + +const express = require('express'); +const cors = require('cors'); +const path = require('path'); +const { errorHandler } = require('./middleware/errorHandler'); + +// 导入服务 +const LibraryService = require('./services/LibraryService'); +const ImageService = require('./services/ImageService'); +const ScanService = require('./services/ScanService'); + +/** + * 创建 Express 应用 + */ +function createApp(dependencies) { + const { + configManager, + dbPool, + scanner, + scanManager, + lightweightWatcher, + io + } = dependencies; + + const app = express(); + + // 中间件 + app.use(cors()); + app.use(express.json()); + + // 初始化服务 + const libraryService = new LibraryService( + configManager, + dbPool, + scanManager, + lightweightWatcher, + io + ); + + const imageService = new ImageService( + configManager, + dbPool + ); + + const scanService = new ScanService( + configManager, + dbPool, + scanner, + scanManager, + io + ); + + // 将服务注入到 app 中,供路由使用 + app.set('libraryService', libraryService); + app.set('imageService', imageService); + app.set('scanService', scanService); + + // API 路由 + const libraryRouter = require('./routes/library'); + const imageRouter = require('./routes/image'); + const scanRouter = require('./routes/scan'); + + app.use('/api/library', libraryRouter); + app.use('/api/image', imageRouter); + app.use('/api/scan', scanRouter); + + // 健康检查 + app.get('/api/health', (req, res) => { + res.json({ + success: true, + status: 'ok', + timestamp: Date.now() + }); + }); + + // 静态文件服务(前端) + const FRONTEND_DIST = process.env.FRONTEND_DIST; + if (FRONTEND_DIST) { + app.use(express.static(FRONTEND_DIST)); + app.get('*', (req, res) => { + res.sendFile(path.join(FRONTEND_DIST, 'index.html')); + }); + } + + // 错误处理中间件(必须放在最后) + app.use(errorHandler); + + return app; +} + +module.exports = { createApp }; diff --git a/flypic/app/server/src/config/constants.js b/flypic/app/server/src/config/constants.js new file mode 100644 index 0000000..b3fd70c --- /dev/null +++ b/flypic/app/server/src/config/constants.js @@ -0,0 +1,62 @@ +/** + * 应用常量配置 + */ + +module.exports = { + // 支持的图片格式 + SUPPORTED_FORMATS: ['jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'tiff'], + + // 缩略图配置 + THUMBNAIL: { + SIZES: { + SMALL: 200, + MEDIUM: 480, + LARGE: 800 + }, + QUALITY: 80, + FORMAT: 'webp', + SHARD_LENGTH: 2 // 分片目录长度 + }, + + // 分页配置 + PAGINATION: { + DEFAULT_SIZE: 100, + MAX_SIZE: 500 + }, + + // 扫描配置 + SCAN: { + BATCH_SIZE: 50, + CONCURRENT_LIMIT: 10, + PROGRESS_UPDATE_INTERVAL: 100 + }, + + // 内存配置 + MEMORY: { + WARNING_THRESHOLD_MB: 200, + DANGER_THRESHOLD_MB: 300, + CACHE_SIZE_KB: 4096, + CLEANUP_INTERVAL_MS: 60000, + DB_IDLE_TIMEOUT_MS: 300000 + }, + + // 数据库配置 + DATABASE: { + PRAGMA: { + journal_mode: 'DELETE', + synchronous: 'NORMAL', + cache_size: -4096, + temp_store: 'FILE', + page_size: 4096, + mmap_size: 0 + } + }, + + // 路径配置 + PATHS: { + FLYPIC_DIR: '.flypic', + THUMBNAILS_DIR: 'thumbnails', + DATABASE_FILE: 'metadata.db', + CONFIG_FILE: 'config.json' + } +}; diff --git a/flypic/app/server/src/config/index.js b/flypic/app/server/src/config/index.js new file mode 100644 index 0000000..aafc71f --- /dev/null +++ b/flypic/app/server/src/config/index.js @@ -0,0 +1,42 @@ +/** + * 配置管理入口 + */ + +const constants = require('./constants'); +const path = require('path'); + +/** + * 获取 FlyPic 目录路径 + */ +function getFlypicPath(libraryPath) { + return path.join(libraryPath, constants.PATHS.FLYPIC_DIR); +} + +/** + * 获取缩略图目录路径 + */ +function getThumbnailsPath(libraryPath) { + return path.join(libraryPath, constants.PATHS.FLYPIC_DIR, constants.PATHS.THUMBNAILS_DIR); +} + +/** + * 获取数据库文件路径 + */ +function getDatabasePath(libraryPath) { + return path.join(libraryPath, constants.PATHS.FLYPIC_DIR, constants.PATHS.DATABASE_FILE); +} + +/** + * 获取配置文件路径 + */ +function getConfigPath(libraryPath) { + return path.join(libraryPath, constants.PATHS.FLYPIC_DIR, constants.PATHS.CONFIG_FILE); +} + +module.exports = { + constants, + getFlypicPath, + getThumbnailsPath, + getDatabasePath, + getConfigPath +}; diff --git a/flypic/app/server/src/middleware/errorHandler.js b/flypic/app/server/src/middleware/errorHandler.js new file mode 100644 index 0000000..8f582ff --- /dev/null +++ b/flypic/app/server/src/middleware/errorHandler.js @@ -0,0 +1,97 @@ +/** + * 统一错误处理中间件 + */ + +/** + * 应用错误类 + */ +class AppError extends Error { + constructor(message, statusCode = 500, code = 'INTERNAL_ERROR') { + super(message); + this.statusCode = statusCode; + this.code = code; + this.isOperational = true; + Error.captureStackTrace(this, this.constructor); + } +} + +/** + * 验证错误 + */ +class ValidationError extends AppError { + constructor(message, field = null) { + super(message, 400, 'VALIDATION_ERROR'); + this.field = field; + } +} + +/** + * 资源未找到错误 + */ +class NotFoundError extends AppError { + constructor(resource, id = null) { + super( + `${resource} not found${id ? `: ${id}` : ''}`, + 404, + 'NOT_FOUND' + ); + this.resource = resource; + this.id = id; + } +} + +/** + * 冲突错误 + */ +class ConflictError extends AppError { + constructor(message) { + super(message, 409, 'CONFLICT'); + } +} + +/** + * 错误处理中间件 + */ +const errorHandler = (err, req, res, next) => { + // 操作性错误(预期的错误) + if (err.isOperational) { + return res.status(err.statusCode).json({ + success: false, + error: { + code: err.code, + message: err.message, + ...(err.field && { field: err.field }) + } + }); + } + + // 编程错误(未预期的错误) + console.error('💥 Unexpected Error:', err); + + res.status(500).json({ + success: false, + error: { + code: 'INTERNAL_ERROR', + message: process.env.NODE_ENV === 'development' + ? err.message + : 'Internal server error', + ...(process.env.NODE_ENV === 'development' && { stack: err.stack }) + } + }); +}; + +/** + * 异步路由处理器包装 + */ +const asyncHandler = (fn) => (req, res, next) => { + Promise.resolve(fn(req, res, next)).catch(next); +}; + +module.exports = { + AppError, + ValidationError, + NotFoundError, + ConflictError, + errorHandler, + asyncHandler +}; diff --git a/flypic/app/server/src/middleware/validator.js b/flypic/app/server/src/middleware/validator.js new file mode 100644 index 0000000..a9c14b8 --- /dev/null +++ b/flypic/app/server/src/middleware/validator.js @@ -0,0 +1,67 @@ +/** + * 请求参数验证中间件 + */ + +const { ValidationError } = require('./errorHandler'); + +/** + * 验证必需参数 + */ +function validateRequired(fields) { + return (req, res, next) => { + const source = req.method === 'GET' ? req.query : req.body; + + for (const field of fields) { + if (!source[field]) { + return next(new ValidationError(`${field} is required`, field)); + } + } + + next(); + }; +} + +/** + * 验证素材库 ID + */ +function validateLibraryId(req, res, next) { + const libraryId = req.params.id || req.query.libraryId || req.body.libraryId; + + if (!libraryId) { + return next(new ValidationError('Library ID is required', 'libraryId')); + } + + req.libraryId = libraryId; + next(); +} + +/** + * 验证分页参数 + */ +function validatePagination(req, res, next) { + const { offset, limit } = req.query; + + if (offset !== undefined) { + const offsetNum = parseInt(offset, 10); + if (isNaN(offsetNum) || offsetNum < 0) { + return next(new ValidationError('Invalid offset', 'offset')); + } + req.pagination = { offset: offsetNum }; + } + + if (limit !== undefined) { + const limitNum = parseInt(limit, 10); + if (isNaN(limitNum) || limitNum < 1 || limitNum > 500) { + return next(new ValidationError('Invalid limit (1-500)', 'limit')); + } + req.pagination = { ...req.pagination, limit: limitNum }; + } + + next(); +} + +module.exports = { + validateRequired, + validateLibraryId, + validatePagination +}; diff --git a/flypic/app/server/src/models/BaseModel.js b/flypic/app/server/src/models/BaseModel.js new file mode 100644 index 0000000..d5a43c8 --- /dev/null +++ b/flypic/app/server/src/models/BaseModel.js @@ -0,0 +1,44 @@ +/** + * 基础数据模型 + * 提供通用的数据库操作方法 + */ + +class BaseModel { + constructor(db) { + this.db = db; + } + + /** + * 执行查询并返回单条记录 + */ + findOne(query, params = []) { + const stmt = this.db.prepare(query); + return stmt.get(...params); + } + + /** + * 执行查询并返回多条记录 + */ + findMany(query, params = []) { + const stmt = this.db.prepare(query); + return stmt.all(...params); + } + + /** + * 执行插入/更新/删除操作 + */ + execute(query, params = []) { + const stmt = this.db.prepare(query); + return stmt.run(...params); + } + + /** + * 执行事务 + */ + transaction(fn) { + const transaction = this.db.transaction(fn); + return transaction(); + } +} + +module.exports = BaseModel; diff --git a/flypic/app/server/src/models/FolderModel.js b/flypic/app/server/src/models/FolderModel.js new file mode 100644 index 0000000..148a1dc --- /dev/null +++ b/flypic/app/server/src/models/FolderModel.js @@ -0,0 +1,115 @@ +/** + * 文件夹数据模型 + */ + +const BaseModel = require('./BaseModel'); +const { mapFolderForFrontend } = require('../utils/fieldMapper'); + +class FolderModel extends BaseModel { + /** + * 根据路径查找文件夹 + */ + findByPath(path) { + const query = 'SELECT * FROM folders WHERE path = ?'; + const folder = this.findOne(query, [path]); + return folder ? mapFolderForFrontend(folder) : null; + } + + /** + * 获取所有文件夹 + */ + findAll() { + const query = 'SELECT * FROM folders ORDER BY path'; + return this.findMany(query).map(mapFolderForFrontend); + } + + /** + * 获取文件夹树 + */ + getTree() { + const folders = this.findAll(); + return this._buildTree(folders); + } + + /** + * 插入文件夹 + */ + insert(data) { + const query = ` + INSERT OR REPLACE INTO folders + (path, parent_path, name, image_count, last_scan) + VALUES (?, ?, ?, ?, ?) + `; + + return this.execute(query, [ + data.path, + data.parentPath || '', + data.name, + data.imageCount || 0, + data.lastScan || Date.now() + ]); + } + + /** + * 更新文件夹图片数量 + */ + updateImageCount(path) { + const query = ` + UPDATE folders + SET image_count = ( + SELECT COUNT(*) FROM images + WHERE folder = ? OR folder LIKE ? + ) + WHERE path = ? + `; + return this.execute(query, [path, `${path}/%`, path]); + } + + /** + * 删除文件夹 + */ + deleteByPath(path) { + const query = 'DELETE FROM folders WHERE path = ?'; + return this.execute(query, [path]); + } + + /** + * 按前缀批量删除 + */ + deleteByPrefix(prefix) { + const query = 'DELETE FROM folders WHERE path = ? OR path LIKE ?'; + return this.execute(query, [prefix, `${prefix}/%`]); + } + + /** + * 构建文件夹树 + */ + _buildTree(folders) { + const folderMap = new Map(); + const rootFolders = []; + + // 第一遍:创建映射 + folders.forEach(folder => { + folderMap.set(folder.path, { ...folder, children: [] }); + }); + + // 第二遍:构建树结构 + folders.forEach(folder => { + const node = folderMap.get(folder.path); + if (!folder.parentPath || folder.parentPath === '') { + rootFolders.push(node); + } else { + const parent = folderMap.get(folder.parentPath); + if (parent) { + parent.children.push(node); + } else { + rootFolders.push(node); + } + } + }); + + return rootFolders; + } +} + +module.exports = FolderModel; diff --git a/flypic/app/server/src/models/ImageModel.js b/flypic/app/server/src/models/ImageModel.js new file mode 100644 index 0000000..f8e1c26 --- /dev/null +++ b/flypic/app/server/src/models/ImageModel.js @@ -0,0 +1,222 @@ +/** + * 图片数据模型 + */ + +const BaseModel = require('./BaseModel'); +const { mapImageForFrontend } = require('../utils/fieldMapper'); + +class ImageModel extends BaseModel { + /** + * 根据 ID 查找图片 + */ + findById(id) { + const query = 'SELECT * FROM images WHERE id = ?'; + const image = this.findOne(query, [id]); + return image ? mapImageForFrontend(image) : null; + } + + /** + * 根据路径查找图片 + */ + findByPath(path) { + const query = 'SELECT * FROM images WHERE path = ?'; + const image = this.findOne(query, [path]); + return image ? mapImageForFrontend(image) : null; + } + + /** + * 搜索图片(支持分页) + */ + search(filters = {}, pagination = null) { + const { query, params } = this._buildSearchQuery(filters, pagination); + + // 获取总数(不包含分页参数) + const { query: countQueryBase, params: countParams } = this._buildSearchQuery(filters, null); + const countQuery = countQueryBase + .replace('SELECT *', 'SELECT COUNT(*) as total') + .split('ORDER BY')[0]; + const { total } = this.findOne(countQuery, countParams); + + // 获取数据 + const images = this.findMany(query, params).map(mapImageForFrontend); + + // 统一返回对象格式 + if (pagination) { + return { + images, + total, + offset: pagination.offset, + limit: pagination.limit, + hasMore: pagination.offset + images.length < total + }; + } + + // 无分页时也返回对象格式 + return { + images, + total + }; + } + + /** + * 插入图片 + */ + insert(data) { + const query = ` + INSERT OR REPLACE INTO images + (path, filename, folder, size, width, height, format, file_type, + created_at, modified_at, file_hash, thumbnail_path, thumbnail_size, indexed_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `; + + return this.execute(query, [ + data.path, + data.filename, + data.folder, + data.size, + data.width, + data.height, + data.format, + data.fileType || 'image', + data.createdAt, + data.modifiedAt, + data.fileHash, + data.thumbnailPath, + data.thumbnailSize, + Date.now() + ]); + } + + /** + * 批量插入图片 + */ + insertBatch(images) { + const query = ` + INSERT OR REPLACE INTO images + (path, filename, folder, size, width, height, format, file_type, + created_at, modified_at, file_hash, thumbnail_path, thumbnail_size, indexed_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `; + + return this.transaction(() => { + const stmt = this.db.prepare(query); + for (const data of images) { + stmt.run( + data.path, data.filename, data.folder, data.size, + data.width, data.height, data.format, data.fileType || 'image', + data.createdAt, data.modifiedAt, data.fileHash, + data.thumbnailPath, data.thumbnailSize, Date.now() + ); + } + }); + } + + /** + * 更新图片 + */ + update(path, data) { + const fields = []; + const params = []; + + Object.entries(data).forEach(([key, value]) => { + fields.push(`${key} = ?`); + params.push(value); + }); + + params.push(path); + + const query = `UPDATE images SET ${fields.join(', ')} WHERE path = ?`; + return this.execute(query, params); + } + + /** + * 删除图片 + */ + deleteByPath(path) { + const query = 'DELETE FROM images WHERE path = ?'; + return this.execute(query, [path]); + } + + /** + * 按文件夹前缀批量删除 + */ + deleteByFolderPrefix(folderPrefix) { + const query = 'DELETE FROM images WHERE folder = ? OR folder LIKE ?'; + return this.execute(query, [folderPrefix, `${folderPrefix}/%`]); + } + + /** + * 获取图片总数 + */ + count(filters = {}) { + const { query, params } = this._buildSearchQuery(filters); + const countQuery = query + .replace('SELECT *', 'SELECT COUNT(*) as count') + .split('ORDER BY')[0]; + const { count } = this.findOne(countQuery, params); + return count; + } + + /** + * 构建搜索查询 + */ + _buildSearchQuery(filters = {}, pagination = null) { + let query = 'SELECT * FROM images WHERE 1=1'; + const params = []; + + // 关键词搜索(AND 逻辑) + if (filters.keywords) { + const terms = filters.keywords.trim().split(/\s+/); + terms.forEach(term => { + query += ' AND filename LIKE ?'; + params.push(`%${term}%`); + }); + } + + // 文件夹过滤(包含子文件夹) + if (filters.folder) { + query += ' AND (folder = ? OR folder LIKE ?)'; + params.push(filters.folder, `${filters.folder}/%`); + } + + // 格式过滤 + if (filters.formats && filters.formats.length > 0) { + const placeholders = filters.formats.map(() => '?').join(','); + query += ` AND format IN (${placeholders})`; + params.push(...filters.formats); + } + + // 大小过滤 + if (filters.minSize) { + query += ' AND size >= ?'; + params.push(filters.minSize); + } + if (filters.maxSize) { + query += ' AND size <= ?'; + params.push(filters.maxSize); + } + + // 日期过滤 + if (filters.startDate) { + query += ' AND created_at >= ?'; + params.push(filters.startDate); + } + if (filters.endDate) { + query += ' AND created_at <= ?'; + params.push(filters.endDate); + } + + // 排序 + query += ' ORDER BY created_at DESC'; + + // 分页 + if (pagination) { + query += ' LIMIT ? OFFSET ?'; + params.push(pagination.limit, pagination.offset); + } + + return { query, params }; + } +} + +module.exports = ImageModel; diff --git a/flypic/app/server/src/routes/image.js b/flypic/app/server/src/routes/image.js new file mode 100644 index 0000000..418f56e --- /dev/null +++ b/flypic/app/server/src/routes/image.js @@ -0,0 +1,170 @@ +/** + * 图片路由(新架构) + * 薄层路由,业务逻辑在 Service 层 + */ + +const express = require('express'); +const router = express.Router(); +const path = require('path'); +const fs = require('fs'); +const { asyncHandler } = require('../middleware/errorHandler'); +const { validatePagination } = require('../middleware/validator'); +const { getFlypicPath } = require('../config'); + +// 服务实例(从 app 中获取) +let imageService; + +router.use((req, res, next) => { + if (!imageService) { + imageService = req.app.get('imageService'); + } + next(); +}); + +/** + * 搜索图片 + * GET /api/image?libraryId=xxx&keywords=xxx&folder=xxx&offset=0&limit=100 + */ +router.get('/', + validatePagination, + asyncHandler(async (req, res) => { + const { libraryId, keywords, folder, formats, offset, limit } = req.query; + + const filters = {}; + if (keywords) filters.keywords = keywords; + if (folder) filters.folder = folder; + if (formats) filters.formats = formats.split(','); + + const pagination = (offset !== undefined && limit !== undefined) + ? { offset: parseInt(offset), limit: parseInt(limit) } + : null; + + const result = await imageService.searchImages(libraryId, filters, pagination); + res.json({ success: true, data: result }); + }) +); + +/** + * 获取图片总数 + * GET /api/image/count?libraryId=xxx + */ +router.get('/count', asyncHandler(async (req, res) => { + const { libraryId } = req.query; + const count = await imageService.getImageCount(libraryId); + res.json({ success: true, data: { count } }); +})); + +/** + * 获取图片统计 + * GET /api/image/stats?libraryId=xxx + */ +router.get('/stats', asyncHandler(async (req, res) => { + const { libraryId } = req.query; + const stats = await imageService.getImageStats(libraryId); + res.json({ success: true, data: stats }); +})); + +/** + * 获取文件夹列表 + * GET /api/image/folders?libraryId=xxx + */ +router.get('/folders', asyncHandler(async (req, res) => { + const { libraryId } = req.query; + const folders = await imageService.getFolders(libraryId); + res.json({ success: true, data: { folders } }); +})); + +/** + * 获取缓存元数据 + * GET /api/image/cache-meta?libraryId=xxx + */ +router.get('/cache-meta', asyncHandler(async (req, res) => { + const { libraryId } = req.query; + const meta = await imageService.getCacheMeta(libraryId); + res.json({ success: true, data: meta }); +})); + +/** + * 获取图片详情 + * GET /api/image/:id?libraryId=xxx + */ +router.get('/:id', asyncHandler(async (req, res) => { + const { id } = req.params; + const { libraryId } = req.query; + const image = await imageService.getImageById(libraryId, id); + res.json({ success: true, data: image }); +})); + +/** + * 获取缩略图 + * GET /api/image/thumbnail/:libraryId/:filename + * 使用分片结构:.flypic/thumbnails/ab/hash.webp + */ +router.get('/thumbnail/:libraryId/:filename', (req, res) => { + const { libraryId, filename } = req.params; + + try { + const config = require('../../utils/config').loadConfig(); + + // 尝试两种方式查找:数字和字符串 + let library = config.libraries.find(lib => lib.id === parseInt(libraryId)); + if (!library) { + library = config.libraries.find(lib => lib.id == libraryId); + } + + if (!library) { + return res.status(404).send('Library not found'); + } + + // 使用分片结构:取文件名前2个字符作为分片目录 + const hash = filename.replace(/\.[^/.]+$/, ''); + const shard = hash.slice(0, 2); + const flypicPath = getFlypicPath(library.path); + const thumbnailPath = path.join(flypicPath, 'thumbnails', shard, filename); + + if (!fs.existsSync(thumbnailPath)) { + return res.status(404).send('Thumbnail not found'); + } + + res.sendFile(thumbnailPath); + } catch (error) { + console.error('❌ 缩略图错误:', error.message); + res.status(500).send('Error serving thumbnail'); + } +}); + +/** + * 获取原图 + * GET /api/image/original/:libraryId/:path + */ +router.get('/original/:libraryId/*', (req, res) => { + const { libraryId } = req.params; + const imagePath = req.params[0]; // 获取通配符匹配的路径 + + try { + const config = require('../../utils/config').loadConfig(); + + // 尝试两种方式查找:数字和字符串 + let library = config.libraries.find(lib => lib.id === parseInt(libraryId)); + if (!library) { + library = config.libraries.find(lib => lib.id == libraryId); + } + + if (!library) { + return res.status(404).send('Library not found'); + } + + const fullPath = path.join(library.path, imagePath); + + if (!fs.existsSync(fullPath)) { + return res.status(404).send('Image not found'); + } + + res.sendFile(fullPath); + } catch (error) { + console.error('Error serving original image:', error); + res.status(500).send('Error serving image'); + } +}); + +module.exports = router; diff --git a/flypic/app/server/src/routes/library.js b/flypic/app/server/src/routes/library.js new file mode 100644 index 0000000..11d6007 --- /dev/null +++ b/flypic/app/server/src/routes/library.js @@ -0,0 +1,109 @@ +/** + * 素材库路由(新架构) + * 薄层路由,业务逻辑在 Service 层 + */ + +const express = require('express'); +const router = express.Router(); +const { asyncHandler } = require('../middleware/errorHandler'); +const { validateRequired } = require('../middleware/validator'); + +// 服务实例(从 app 中获取) +let libraryService; + +router.use((req, res, next) => { + if (!libraryService) { + libraryService = req.app.get('libraryService'); + } + next(); +}); + +/** + * 获取所有素材库 + * GET /api/library + */ +router.get('/', asyncHandler(async (req, res) => { + const data = libraryService.getAllLibraries(); + res.json({ success: true, data }); +})); + +/** + * 创建素材库 + * POST /api/library + * Body: { name, path } + */ +router.post('/', + validateRequired(['name', 'path']), + asyncHandler(async (req, res) => { + const { name, path } = req.body; + const result = await libraryService.createLibrary(name, path); + res.json({ success: true, data: result }); + }) +); + +/** + * 更新素材库 + * PUT /api/library/:id + * Body: { name?, path? } + */ +router.put('/:id', asyncHandler(async (req, res) => { + const { id } = req.params; + const result = await libraryService.updateLibrary(id, req.body); + res.json({ success: true, data: result }); +})); + +/** + * 删除素材库 + * DELETE /api/library/:id + */ +router.delete('/:id', asyncHandler(async (req, res) => { + const { id } = req.params; + const result = await libraryService.deleteLibrary(id); + res.json({ success: true, data: result }); +})); + +/** + * 设置当前素材库 + * POST /api/library/:id/set-current + */ +router.post('/:id/set-current', asyncHandler(async (req, res) => { + const { id } = req.params; + const result = await libraryService.setCurrentLibrary(id); + res.json({ success: true, data: result }); +})); + +/** + * 更新偏好设置 + * PUT /api/library/preferences + * Body: { preferences } + */ +router.put('/preferences', asyncHandler(async (req, res) => { + const result = libraryService.updatePreferences(req.body); + res.json({ success: true, data: result }); +})); + +/** + * 更新主题 + * PUT /api/library/theme + * Body: { theme } + */ +router.put('/theme', + validateRequired(['theme']), + asyncHandler(async (req, res) => { + const { theme } = req.body; + const result = libraryService.updateTheme(theme); + res.json({ success: true, data: result }); + }) +); + +/** + * 获取素材库统计 + * GET /api/library/:id/stats + */ +router.get('/:id/stats', asyncHandler(async (req, res) => { + const { id } = req.params; + const result = await libraryService.getLibraryStats(id); + res.json({ success: true, data: result }); +})); + +module.exports = router; diff --git a/flypic/app/server/src/routes/scan.js b/flypic/app/server/src/routes/scan.js new file mode 100644 index 0000000..a017668 --- /dev/null +++ b/flypic/app/server/src/routes/scan.js @@ -0,0 +1,82 @@ +/** + * 扫描路由(新架构) + * 薄层路由,业务逻辑在 Service 层 + */ + +const express = require('express'); +const router = express.Router(); +const { asyncHandler } = require('../middleware/errorHandler'); +const { validateRequired } = require('../middleware/validator'); + +// 服务实例(从 app 中获取) +let scanService; + +router.use((req, res, next) => { + if (!scanService) { + scanService = req.app.get('scanService'); + } + next(); +}); + +/** + * 全量扫描 + * POST /api/scan/full + * Body: { libraryId, wait? } + */ +router.post('/full', + validateRequired(['libraryId']), + asyncHandler(async (req, res) => { + const { libraryId, wait = false } = req.body; + const result = await scanService.fullScan(libraryId, wait); + res.json({ success: true, data: result }); + }) +); + +/** + * 增量同步 + * POST /api/scan/sync + * Body: { libraryId, wait? } + */ +router.post('/sync', + validateRequired(['libraryId']), + asyncHandler(async (req, res) => { + const { libraryId, wait = false } = req.body; + const result = await scanService.incrementalSync(libraryId, wait); + res.json({ success: true, data: result }); + }) +); + +/** + * 获取扫描状态 + * GET /api/scan/status/:libraryId + */ +router.get('/status/:libraryId', asyncHandler(async (req, res) => { + const { libraryId } = req.params; + const result = scanService.getScanStatus(libraryId); + res.json({ success: true, data: result }); +})); + +/** + * 获取所有活跃的扫描状态 + * GET /api/scan/active-states + */ +router.get('/active-states', asyncHandler(async (req, res) => { + const result = scanService.getAllActiveStates(); + res.json({ success: true, data: result }); +})); + +/** + * 修复文件夹路径 + * POST /api/scan/fix-folders + * Body: { libraryId } + */ +router.post('/fix-folders', + validateRequired(['libraryId']), + asyncHandler(async (req, res) => { + const { libraryId } = req.body; + const result = await scanService.fixFolders(libraryId); + res.json({ success: true, data: result }); + }) +); + +module.exports = router; diff --git a/flypic/app/server/src/services/ImageService.js b/flypic/app/server/src/services/ImageService.js new file mode 100644 index 0000000..c0d9e19 --- /dev/null +++ b/flypic/app/server/src/services/ImageService.js @@ -0,0 +1,181 @@ +/** + * 图片服务层 + * 封装图片相关的业务逻辑 + */ + +const { NotFoundError, ValidationError } = require('../middleware/errorHandler'); +const ImageModel = require('../models/ImageModel'); +const FolderModel = require('../models/FolderModel'); + +class ImageService { + constructor(configManager, dbPool) { + this.configManager = configManager; + this.dbPool = dbPool; + } + + /** + * 搜索图片 + */ + async searchImages(libraryId, filters = {}, pagination = null) { + const library = this._getLibrary(libraryId); + const db = this.dbPool.acquire(library.path); + + try { + const imageModel = new ImageModel(db.db); + return imageModel.search(filters, pagination); + } finally { + this.dbPool.release(library.path); + } + } + + /** + * 获取图片详情 + */ + async getImageById(libraryId, imageId) { + const library = this._getLibrary(libraryId); + const db = this.dbPool.acquire(library.path); + + try { + const imageModel = new ImageModel(db.db); + const image = imageModel.findById(imageId); + + if (!image) { + throw new NotFoundError('Image', imageId); + } + + return image; + } finally { + this.dbPool.release(library.path); + } + } + + /** + * 根据路径获取图片 + */ + async getImageByPath(libraryId, imagePath) { + const library = this._getLibrary(libraryId); + const db = this.dbPool.acquire(library.path); + + try { + const imageModel = new ImageModel(db.db); + const image = imageModel.findByPath(imagePath); + + if (!image) { + throw new NotFoundError('Image', imagePath); + } + + return image; + } finally { + this.dbPool.release(library.path); + } + } + + /** + * 获取图片总数 + */ + async getImageCount(libraryId, filters = {}) { + const library = this._getLibrary(libraryId); + const db = this.dbPool.acquire(library.path); + + try { + const imageModel = new ImageModel(db.db); + return imageModel.count(filters); + } finally { + this.dbPool.release(library.path); + } + } + + /** + * 获取图片统计信息 + */ + async getImageStats(libraryId) { + const library = this._getLibrary(libraryId); + const db = this.dbPool.acquire(library.path); + + try { + const stats = db.db.prepare(` + SELECT + COUNT(*) as total, + SUM(size) as totalSize, + AVG(size) as avgSize, + MAX(size) as maxSize, + MIN(size) as minSize, + COUNT(DISTINCT format) as formatCount, + COUNT(DISTINCT folder) as folderCount + FROM images + `).get(); + + const formatStats = db.db.prepare(` + SELECT format, COUNT(*) as count + FROM images + GROUP BY format + ORDER BY count DESC + `).all(); + + return { + ...stats, + formats: formatStats + }; + } finally { + this.dbPool.release(library.path); + } + } + + /** + * 获取文件夹列表 + */ + async getFolders(libraryId) { + const library = this._getLibrary(libraryId); + const db = this.dbPool.acquire(library.path); + + try { + const folderModel = new FolderModel(db.db); + return folderModel.getTree(); + } finally { + this.dbPool.release(library.path); + } + } + + /** + * 获取缓存元数据 + */ + async getCacheMeta(libraryId) { + const library = this._getLibrary(libraryId); + const db = this.dbPool.acquire(library.path); + + try { + const result = db.db.prepare(` + SELECT + COUNT(*) as totalImages, + COUNT(DISTINCT folder) as totalFolders, + MAX(indexed_at) as lastIndexed + FROM images + `).get(); + + return { + libraryId, + ...result, + dbPath: library.path + }; + } finally { + this.dbPool.release(library.path); + } + } + + /** + * 获取素材库对象 + * @private + */ + _getLibrary(libraryId) { + const config = this.configManager.load(); + const library = config.libraries.find(lib => lib.id === libraryId); + + if (!library) { + throw new NotFoundError('Library', libraryId); + } + + return library; + } +} + +module.exports = ImageService; diff --git a/flypic/app/server/src/services/LibraryService.js b/flypic/app/server/src/services/LibraryService.js new file mode 100644 index 0000000..06097f2 --- /dev/null +++ b/flypic/app/server/src/services/LibraryService.js @@ -0,0 +1,275 @@ +/** + * 素材库服务层 + * 封装素材库相关的业务逻辑 + */ + +const fs = require('fs'); +const path = require('path'); +const { NotFoundError, ValidationError } = require('../middleware/errorHandler'); +const { getFlypicPath, getDatabasePath } = require('../config'); + +class LibraryService { + constructor(configManager, dbPool, scanManager, lightweightWatcher, io) { + this.configManager = configManager; + this.dbPool = dbPool; + this.scanManager = scanManager; + this.lightweightWatcher = lightweightWatcher; + this.io = io; + } + + /** + * 获取所有素材库 + */ + getAllLibraries() { + const config = this.configManager.load(); + return { + libraries: config.libraries || [], + currentLibraryId: config.currentLibraryId, + theme: config.theme || 'light', + preferences: config.preferences || {} + }; + } + + /** + * 创建新素材库 + */ + async createLibrary(name, libraryPath) { + // 验证参数 + if (!name || !libraryPath) { + throw new ValidationError('Name and path are required'); + } + + // 规范化路径 + const normalizedPath = path.normalize(libraryPath); + console.log(`[LibraryService] Creating library: name=${name}, path=${normalizedPath}`); + + if (!fs.existsSync(normalizedPath)) { + console.log(`[LibraryService] Path does not exist: ${normalizedPath}`); + throw new ValidationError('Path does not exist', 'path'); + } + + // 检查文件夹访问权限 + try { + // 尝试读取目录 + fs.readdirSync(normalizedPath); + + // 尝试在目录中创建测试文件(检查写权限) + const testFile = path.join(normalizedPath, '.flypic-test'); + try { + fs.writeFileSync(testFile, 'test'); + fs.unlinkSync(testFile); + } catch (writeError) { + console.log(`[LibraryService] No write permission: ${normalizedPath}`); + throw new ValidationError( + '无法访问该文件夹。请在飞牛 fnOS 的"数据共享"中将此文件夹添加到 FlyPic 应用的访问权限。', + 'permission' + ); + } + } catch (readError) { + if (readError.code === 'EACCES' || readError.code === 'EPERM') { + console.log(`[LibraryService] No access permission: ${normalizedPath}`); + throw new ValidationError( + '无法访问该文件夹。请在飞牛 fnOS 的"数据共享"中将此文件夹添加到 FlyPic 应用的访问权限。', + 'permission' + ); + } + // 如果不是权限错误,继续抛出 + if (readError.name !== 'ValidationError') { + throw readError; + } + throw readError; + } + + // 检查路径是否已存在 + const config = this.configManager.load(); + const existingLib = config.libraries.find(lib => lib.path === normalizedPath); + if (existingLib) { + throw new ValidationError('Library path already exists', 'path'); + } + + // 创建素材库 + const id = this.configManager.addLibrary(name, normalizedPath); + + // 检查是否有现有索引 + const flypicDir = getFlypicPath(normalizedPath); + const dbPath = getDatabasePath(normalizedPath); + const hasExistingIndex = fs.existsSync(flypicDir) && fs.existsSync(dbPath); + + return { + id, + hasExistingIndex, + message: hasExistingIndex + ? 'Library created with existing index' + : 'Library created, please scan to build index' + }; + } + + /** + * 更新素材库 + */ + updateLibrary(id, updates) { + const config = this.configManager.load(); + const library = config.libraries.find(lib => lib.id === id); + + if (!library) { + throw new NotFoundError('Library', id); + } + + // 验证更新的路径是否存在 + if (updates.path && !fs.existsSync(updates.path)) { + throw new ValidationError('Path does not exist', 'path'); + } + + const success = this.configManager.updateLibrary(id, updates); + return { success }; + } + + /** + * 删除素材库 + */ + async deleteLibrary(id) { + const config = this.configManager.load(); + const library = config.libraries.find(lib => lib.id === id); + + if (!library) { + throw new NotFoundError('Library', id); + } + + // 清理资源 + await this._cleanupLibraryResources(id, library.path); + + // 删除配置 + this.configManager.removeLibrary(id); + + return { + success: true, + path: library.path, + message: 'Library deleted successfully' + }; + } + + /** + * 设置当前素材库 + */ + async setCurrentLibrary(id) { + const config = this.configManager.load(); + const library = config.libraries.find(lib => lib.id === id); + + if (!library) { + throw new NotFoundError('Library', id); + } + + // 切换前清理旧素材库资源 + if (config.currentLibraryId && config.currentLibraryId !== id) { + const oldLibrary = config.libraries.find(lib => lib.id === config.currentLibraryId); + if (oldLibrary) { + await this._cleanupLibraryResources(config.currentLibraryId, oldLibrary.path, false); + } + } + + // 设置新素材库 + this.configManager.setCurrentLibrary(id); + + // 预热数据库连接 + try { + const db = this.dbPool.acquire(library.path); + db.db.prepare('SELECT 1').get(); + this.dbPool.release(library.path); + } catch (e) { + // 忽略预热错误 + } + + // 启动文件监控 + if (this.lightweightWatcher && this.io) { + try { + this.lightweightWatcher.watch(id, library.path, library.name, this.io); + } catch (e) { + console.warn('Failed to start file watcher:', e.message); + } + } + + return { + success: true, + libraryId: id, + message: 'Current library set successfully' + }; + } + + /** + * 更新偏好设置 + */ + updatePreferences(preferences) { + this.configManager.updatePreferences(preferences); + return { success: true }; + } + + /** + * 更新主题 + */ + updateTheme(theme) { + if (!['light', 'dark'].includes(theme)) { + throw new ValidationError('Invalid theme, must be light or dark', 'theme'); + } + + this.configManager.updateTheme(theme); + return { success: true, theme }; + } + + /** + * 清理素材库资源 + * @private + */ + async _cleanupLibraryResources(libraryId, libraryPath, deleteConfig = true) { + // 停止扫描 + if (this.scanManager) { + this.scanManager.clearState(libraryId); + } + + // 停止文件监控 + if (this.lightweightWatcher) { + this.lightweightWatcher.unwatch(libraryId); + } + + // 关闭数据库连接 + if (this.dbPool) { + this.dbPool.close(libraryPath); + } + + // 等待资源释放 + await new Promise(resolve => setTimeout(resolve, 300)); + } + + /** + * 获取素材库统计信息 + */ + async getLibraryStats(libraryId) { + const config = this.configManager.load(); + const library = config.libraries.find(lib => lib.id === libraryId); + + if (!library) { + throw new NotFoundError('Library', libraryId); + } + + const db = this.dbPool.acquire(library.path); + try { + const imageCount = db.db.prepare('SELECT COUNT(*) as count FROM images').get().count; + const folderCount = db.db.prepare('SELECT COUNT(*) as count FROM folders').get().count; + + const sizeResult = db.db.prepare('SELECT SUM(size) as totalSize FROM images').get(); + const totalSize = sizeResult.totalSize || 0; + + return { + libraryId, + imageCount, + folderCount, + totalSize, + path: library.path, + name: library.name + }; + } finally { + this.dbPool.release(library.path); + } + } +} + +module.exports = LibraryService; diff --git a/flypic/app/server/src/services/ScanService.js b/flypic/app/server/src/services/ScanService.js new file mode 100644 index 0000000..519b0e0 --- /dev/null +++ b/flypic/app/server/src/services/ScanService.js @@ -0,0 +1,178 @@ +/** + * 扫描服务层(简化版) + * 无暂停功能,只负责扫描和进度推送 + */ + +const { NotFoundError, ValidationError } = require('../middleware/errorHandler'); + +class ScanService { + constructor(configManager, dbPool, scanner, scanManager, io) { + this.configManager = configManager; + this.dbPool = dbPool; + this.scanner = scanner; + this.scanManager = scanManager; + this.io = io; + } + + /** + * 全量扫描 + */ + async fullScan(libraryId, wait = false) { + const library = this._getLibrary(libraryId); + const db = this.dbPool.acquire(library.path); + + try { + if (this.scanManager.isScanning(libraryId)) { + throw new ValidationError('Scan already in progress', 'libraryId'); + } + + if (wait) { + await this.scanner.scanLibrary( + library.path, + db, + (progress) => this._emitProgress(libraryId, progress), + libraryId + ); + return { success: true, message: 'Scan completed', libraryId }; + } else { + this._startAsyncScan(libraryId, library.path, db); + return { success: true, message: 'Scan started', libraryId, async: true }; + } + } catch (error) { + this.dbPool.release(library.path); + throw error; + } + } + + /** + * 增量同步 + */ + async incrementalSync(libraryId, wait = false) { + const library = this._getLibrary(libraryId); + const db = this.dbPool.acquire(library.path); + + try { + if (this.scanManager.isScanning(libraryId)) { + throw new ValidationError('Scan already in progress', 'libraryId'); + } + + if (wait) { + await this.scanner.syncLibrary( + library.path, + db, + false, + (progress) => this._emitProgress(libraryId, progress) + ); + return { success: true, message: 'Sync completed', libraryId }; + } else { + this._startAsyncSync(libraryId, library.path, db); + return { success: true, message: 'Sync started', libraryId, async: true }; + } + } catch (error) { + this.dbPool.release(library.path); + throw error; + } + } + + /** + * 获取扫描状态 + */ + getScanStatus(libraryId) { + const library = this._getLibrary(libraryId); + const state = this.scanManager.getState(libraryId); + + return { + libraryId, + status: state?.status || 'idle', + progress: state?.progress || null, + startTime: state?.startTime || null + }; + } + + /** + * 获取所有活跃状态 + */ + getAllActiveStates() { + return this.scanManager.getAllActiveStates(); + } + + /** + * 修复文件夹路径 + */ + async fixFolders(libraryId) { + const library = this._getLibrary(libraryId); + const db = this.dbPool.acquire(library.path); + + try { + await this.scanner.fixFolderPaths(library.path, db); + return { success: true, message: 'Folders fixed', libraryId }; + } finally { + this.dbPool.release(library.path); + } + } + + /** + * 启动异步扫描 + */ + _startAsyncScan(libraryId, libraryPath, db) { + this.scanner.scanLibrary( + libraryPath, + db, + (progress) => this._emitProgress(libraryId, progress), + libraryId + ).then(() => { + this._emitComplete(libraryId); + this.dbPool.release(libraryPath); + }).catch((error) => { + this._emitError(libraryId, error); + this.dbPool.release(libraryPath); + }); + } + + /** + * 启动异步同步 + */ + _startAsyncSync(libraryId, libraryPath, db) { + this.scanner.syncLibrary( + libraryPath, + db, + false, + (progress) => this._emitProgress(libraryId, progress) + ).then(() => { + this._emitComplete(libraryId); + this.dbPool.release(libraryPath); + }).catch((error) => { + this._emitError(libraryId, error); + this.dbPool.release(libraryPath); + }); + } + + _emitProgress(libraryId, progress) { + if (this.io) { + this.io.emit('scanProgress', { libraryId, ...progress }); + } + } + + _emitComplete(libraryId) { + if (this.io) { + this.io.emit('scanComplete', { libraryId }); + } + } + + _emitError(libraryId, error) { + if (this.io) { + this.io.emit('scanError', { libraryId, error: error.message }); + } + } + + _getLibrary(libraryId) { + const config = this.configManager.load(); + const library = config.libraries.find(lib => lib.id === libraryId); + if (!library) { + throw new NotFoundError('Library', libraryId); + } + return library; + } +} + +module.exports = ScanService; diff --git a/flypic/app/server/src/utils/fieldMapper.js b/flypic/app/server/src/utils/fieldMapper.js new file mode 100644 index 0000000..4087109 --- /dev/null +++ b/flypic/app/server/src/utils/fieldMapper.js @@ -0,0 +1,71 @@ +/** + * 数据库字段映射工具 + * 将 snake_case 转换为 camelCase + */ + +// 数据库字段到前端字段的映射 +const DB_TO_FRONTEND_MAP = { + // Image fields + file_type: 'fileType', + created_at: 'createdAt', + modified_at: 'modifiedAt', + file_hash: 'fileHash', + thumbnail_path: 'thumbnailPath', + thumbnail_size: 'thumbnailSize', + indexed_at: 'indexedAt', + + // Folder fields + parent_path: 'parentPath', + image_count: 'imageCount', + last_scan: 'lastScan' +}; + +/** + * 映射单个对象的字段 + */ +function mapFields(obj, mapping) { + if (!obj) return null; + + const result = {}; + for (const [key, value] of Object.entries(obj)) { + const newKey = mapping[key] || key; + result[newKey] = value; + } + return result; +} + +/** + * 映射图片对象 + */ +function mapImageForFrontend(image) { + return mapFields(image, DB_TO_FRONTEND_MAP); +} + +/** + * 映射文件夹对象 + */ +function mapFolderForFrontend(folder) { + return mapFields(folder, DB_TO_FRONTEND_MAP); +} + +/** + * 批量映射图片数组 + */ +function mapImagesForFrontend(images) { + return images.map(mapImageForFrontend); +} + +/** + * 批量映射文件夹数组 + */ +function mapFoldersForFrontend(folders) { + return folders.map(mapFolderForFrontend); +} + +module.exports = { + mapImageForFrontend, + mapFolderForFrontend, + mapImagesForFrontend, + mapFoldersForFrontend, + mapFields +}; diff --git a/flypic/app/server/src/utils/logger.js b/flypic/app/server/src/utils/logger.js new file mode 100644 index 0000000..9432f22 --- /dev/null +++ b/flypic/app/server/src/utils/logger.js @@ -0,0 +1,31 @@ +/** + * 简单的日志工具 + */ + +const LOG_LEVELS = { + DEBUG: 0, + INFO: 1, + WARN: 2, + ERROR: 3 +}; + +const currentLevel = process.env.LOG_LEVEL + ? LOG_LEVELS[process.env.LOG_LEVEL.toUpperCase()] + : LOG_LEVELS.INFO; + +function log(level, message, ...args) { + if (LOG_LEVELS[level] >= currentLevel) { + const timestamp = new Date().toISOString(); + const prefix = `[${timestamp}] [${level}]`; + console.log(prefix, message, ...args); + } +} + +const logger = { + debug: (message, ...args) => log('DEBUG', message, ...args), + info: (message, ...args) => log('INFO', message, ...args), + warn: (message, ...args) => log('WARN', message, ...args), + error: (message, ...args) => log('ERROR', message, ...args) +}; + +module.exports = logger; diff --git a/flypic/app/server/utils/cleanupManager.js b/flypic/app/server/utils/cleanupManager.js new file mode 100644 index 0000000..b89ad76 --- /dev/null +++ b/flypic/app/server/utils/cleanupManager.js @@ -0,0 +1,233 @@ +/** + * Cleanup Manager + * Executes routine and emergency memory cleanup procedures + */ + +class CleanupManager { + constructor(options = {}) { + this.routineInterval = options.routineInterval || 5000; // 5 seconds + this.dbPool = options.dbPool; + this.caches = new Map(); // name -> cache object with clear() method + + this.routineIntervalId = null; + this.isRunning = false; + this.cleanupCount = 0; + this.lastCleanupTime = 0; + } + + /** + * Start routine cleanup + */ + startRoutineCleanup() { + if (this.isRunning) return; + + console.log('🧹 清理管理器已启动'); + this.isRunning = true; + + this.routineIntervalId = setInterval(() => { + this.executeRoutineCleanup(); + }, this.routineInterval); + } + + /** + * Stop routine cleanup + */ + stopRoutineCleanup() { + if (!this.isRunning) return; + + console.log('🧹 清理管理器已停止'); + + if (this.routineIntervalId) { + clearInterval(this.routineIntervalId); + this.routineIntervalId = null; + } + + this.isRunning = false; + } + + /** + * Execute routine cleanup + * - Clear registered caches + * - Trigger garbage collection (if available) + */ + executeRoutineCleanup() { + const memoryBefore = this.getMemoryStats(); + const rssBefore = memoryBefore.rss / 1024 / 1024; + + try { + // Clear all registered caches + const cachesCleared = this.clearAllCaches(); + + // 强制多次 GC(更激进) + if (global.gc) { + // 执行 5 次 GC 确保内存真正释放 + for (let i = 0; i < 5; i++) { + global.gc(); + } + } + + const memoryAfter = this.getMemoryStats(); + const rssAfter = memoryAfter.rss / 1024 / 1024; + const memoryReclaimed = memoryBefore.heapUsed - memoryAfter.heapUsed; + const rssReclaimed = rssBefore - rssAfter; + + this.cleanupCount++; + this.lastCleanupTime = Date.now(); + + // 只在内存回收显著时输出日志 + if (Math.abs(rssReclaimed) > 10) { + console.log(`🧹 内存清理: ${rssBefore.toFixed(0)}MB → ${rssAfter.toFixed(0)}MB`); + } + + return { + memoryBefore, + memoryAfter, + memoryReclaimed, + cachesCleared, + connectionsCleared: 0 + }; + } catch (error) { + console.error('❌ 清理失败:', error.message); + return null; + } + } + + /** + * Execute emergency cleanup + * - Force close all database connections + * - Clear all caches + * - Force garbage collection multiple times (3+) + */ + executeEmergencyCleanup() { + console.log('🚨 执行紧急内存清理...'); + + const memoryBefore = this.getMemoryStats(); + + try { + // 1. Force close all database connections + let connectionsCleared = 0; + if (this.dbPool) { + try { + this.dbPool.closeAll(); + connectionsCleared = 1; + console.log(' ✓ 数据库连接已关闭'); + } catch (error) { + console.error(' ✗ 关闭连接失败:', error.message); + } + } + + // 2. Clear all registered caches + const cachesCleared = this.clearAllCaches(); + console.log(` ✓ 已清理 ${cachesCleared} 个缓存`); + + // 3. Force garbage collection multiple times (minimum 3) + this.forceGarbageCollection(3); + + const memoryAfter = this.getMemoryStats(); + const memoryReclaimed = memoryBefore.heapUsed - memoryAfter.heapUsed; + + console.log(`✅ 紧急清理完成: 回收 ${(memoryReclaimed / 1024 / 1024).toFixed(0)}MB`); + + return { + memoryBefore, + memoryAfter, + memoryReclaimed, + cachesCleared, + connectionsCleared + }; + } catch (error) { + console.error('❌ 紧急清理失败:', error.message); + return null; + } + } + + /** + * Force garbage collection multiple times + * @param {number} iterations - Number of GC iterations (minimum 3) + */ + forceGarbageCollection(iterations = 3) { + if (!global.gc) return; + + const actualIterations = Math.max(3, iterations); + for (let i = 0; i < actualIterations; i++) { + try { + global.gc(); + } catch (error) { + console.error(` ✗ GC失败 (${i + 1}/${actualIterations}):`, error.message); + } + } + } + + /** + * Clear all registered caches + * @returns {number} Number of caches cleared + */ + clearAllCaches() { + let cleared = 0; + + for (const [name, cache] of this.caches.entries()) { + try { + if (cache && typeof cache.clear === 'function') { + cache.clear(); + cleared++; + } + } catch (error) { + console.error(`❌ 清理缓存失败 "${name}":`, error.message); + } + } + + return cleared; + } + + /** + * Register a cache for cleanup + * @param {string} name - Cache name + * @param {Object} cache - Cache object with clear() method + */ + registerCache(name, cache) { + if (!cache || typeof cache.clear !== 'function') { + console.warn(`⚠️ 缓存 "${name}" 无clear()方法`); + return; + } + + this.caches.set(name, cache); + } + + /** + * Unregister a cache + * @param {string} name - Cache name + */ + unregisterCache(name) { + this.caches.delete(name); + } + + /** + * Get current memory statistics + */ + getMemoryStats() { + const usage = process.memoryUsage(); + return { + heapUsed: usage.heapUsed, + heapTotal: usage.heapTotal, + rss: usage.rss, + external: usage.external, + arrayBuffers: usage.arrayBuffers, + timestamp: Date.now() + }; + } + + /** + * Get cleanup manager status + */ + getStatus() { + return { + isRunning: this.isRunning, + routineInterval: this.routineInterval, + cleanupCount: this.cleanupCount, + lastCleanupTime: this.lastCleanupTime, + registeredCaches: Array.from(this.caches.keys()) + }; + } +} + +module.exports = CleanupManager; diff --git a/flypic/app/server/utils/fileWatcher.js b/flypic/app/server/utils/fileWatcher.js deleted file mode 100644 index e1bc84d..0000000 --- a/flypic/app/server/utils/fileWatcher.js +++ /dev/null @@ -1,242 +0,0 @@ -const { Worker } = require('worker_threads'); -const path = require('path'); -const { getLibrary } = require('./config'); -const { applyChangesFromEvents } = require('./scanner'); -const dbPool = require('../database/dbPool'); - -class FileWatcher { - constructor() { - this.workers = new Map(); // libraryId -> Worker - this.debounceTimers = new Map(); // libraryId -> { timer, forceRebuildFolders } - this.changeBuffers = new Map(); // libraryId -> { filesAdded, filesChanged, filesRemoved, dirsAdded, dirsRemoved } - this.ioRef = null; // Socket.IO 引用 - } - - // 获取或创建变更缓冲区 - _getBuffer(libraryId) { - if (!this.changeBuffers.has(libraryId)) { - this.changeBuffers.set(libraryId, { - filesAdded: new Set(), - filesChanged: new Set(), - filesRemoved: new Set(), - dirsAdded: new Set(), - dirsRemoved: new Set() - }); - } - return this.changeBuffers.get(libraryId); - } - - // 缓冲区事件数量 - _bufferCount(buf) { - return ( - buf.filesAdded.size + - buf.filesChanged.size + - buf.filesRemoved.size + - buf.dirsAdded.size + - buf.dirsRemoved.size - ); - } - - // 启动监控(使用 Worker Thread,不阻塞主线程) - watch(libraryId, io) { - // 保存 io 引用 - this.ioRef = io; - - // 如果已经在监控,先停止 - if (this.workers.has(libraryId)) { - this.unwatch(libraryId); - } - - const library = getLibrary(libraryId); - if (!library) { - console.error(`Library ${libraryId} not found`); - return; - } - - // 检查路径是否存在和可访问 - const fs = require('fs'); - try { - fs.accessSync(library.path, fs.constants.R_OK); - } catch (error) { - const errorMsg = `Cannot access library path: ${library.path} - ${error.message}`; - console.error(errorMsg); - throw new Error(errorMsg); - } - - console.log(`[FileWatcher] Starting worker for: ${library.name} (${library.path})`); - - // 创建 Worker Thread - const workerPath = path.join(__dirname, 'fileWatcherWorker.js'); - const worker = new Worker(workerPath, { - workerData: { - libraryPath: library.path, - libraryName: library.name - } - }); - - // 处理 Worker 消息 - worker.on('message', (msg) => { - this._handleWorkerMessage(libraryId, library, msg); - }); - - worker.on('error', (error) => { - console.error(`[FileWatcher] Worker error for ${library.name}:`, error); - }); - - worker.on('exit', (code) => { - if (code !== 0) { - console.error(`[FileWatcher] Worker exited with code ${code} for ${library.name}`); - } - this.workers.delete(libraryId); - }); - - this.workers.set(libraryId, worker); - } - - // 处理 Worker 发来的消息 - _handleWorkerMessage(libraryId, library, msg) { - switch (msg.type) { - case 'add': - this._getBuffer(libraryId).filesAdded.add(msg.path); - this._debouncedSync(libraryId, library); - break; - case 'unlink': - this._getBuffer(libraryId).filesRemoved.add(msg.path); - this._debouncedSync(libraryId, library); - break; - case 'change': - this._getBuffer(libraryId).filesChanged.add(msg.path); - this._debouncedSync(libraryId, library); - break; - case 'addDir': - this._getBuffer(libraryId).dirsAdded.add(msg.path); - this._debouncedSync(libraryId, library, true); - break; - case 'unlinkDir': - this._getBuffer(libraryId).dirsRemoved.add(msg.path); - this._debouncedSync(libraryId, library, true); - break; - case 'ready': - console.log(`[FileWatcher] Ready for: ${library.name}`); - break; - case 'error': - console.error(`[FileWatcher] Error for ${library.name}:`, msg.message); - break; - case 'closed': - console.log(`[FileWatcher] Closed for: ${library.name}`); - break; - } - } - - // 防抖同步 - _debouncedSync(libraryId, library, forceRebuildFolders = false) { - const buf = this._getBuffer(libraryId); - const changeCount = this._bufferCount(buf); - - // 清除之前的定时器 - if (this.debounceTimers.has(libraryId)) { - const oldTimer = this.debounceTimers.get(libraryId); - clearTimeout(oldTimer.timer); - forceRebuildFolders = forceRebuildFolders || oldTimer.forceRebuildFolders; - } - - // 自适应防抖时间 - let debounceMs = 2000; - if (changeCount <= 1) debounceMs = 800; - else if (changeCount <= 5) debounceMs = 1000; - else if (changeCount <= 20) debounceMs = 1500; - else if (changeCount <= 100) debounceMs = 2000; - else debounceMs = 3000; - - const timer = setTimeout(async () => { - const snapshot = this._getBuffer(libraryId); - // 清空缓冲区 - this.changeBuffers.set(libraryId, { - filesAdded: new Set(), - filesChanged: new Set(), - filesRemoved: new Set(), - dirsAdded: new Set(), - dirsRemoved: new Set() - }); - - const db = dbPool.acquire(library.path); - - try { - const results = await applyChangesFromEvents(library.path, db, { - filesAdded: Array.from(snapshot.filesAdded), - filesChanged: Array.from(snapshot.filesChanged), - filesRemoved: Array.from(snapshot.filesRemoved), - dirsAdded: Array.from(snapshot.dirsAdded), - dirsRemoved: Array.from(snapshot.dirsRemoved) - }); - - if (this.ioRef) { - this.ioRef.emit('scanComplete', { libraryId, results }); - } - console.log(`[FileWatcher] Sync complete for ${library.name}:`, results); - } catch (error) { - console.error(`[FileWatcher] Sync error for ${library.name}:`, error); - if (this.ioRef) { - this.ioRef.emit('scanError', { libraryId, error: error.message }); - } - } finally { - dbPool.release(library.path); - } - - this.debounceTimers.delete(libraryId); - }, debounceMs); - - this.debounceTimers.set(libraryId, { timer, forceRebuildFolders }); - } - - // 停止监控 - unwatch(libraryId) { - const worker = this.workers.get(libraryId); - if (worker) { - // 发送关闭命令给 Worker - worker.postMessage({ type: 'close' }); - // 给 Worker 一些时间优雅关闭,然后强制终止 - setTimeout(() => { - if (this.workers.has(libraryId)) { - worker.terminate(); - this.workers.delete(libraryId); - } - }, 1000); - console.log(`[FileWatcher] Stopping worker for: ${libraryId}`); - } - - // 清除防抖定时器 - if (this.debounceTimers.has(libraryId)) { - const timerObj = this.debounceTimers.get(libraryId); - clearTimeout(timerObj.timer); - this.debounceTimers.delete(libraryId); - } - - // 清空缓冲区 - if (this.changeBuffers.has(libraryId)) { - this.changeBuffers.delete(libraryId); - } - } - - // 停止所有监控 - unwatchAll() { - for (const libraryId of this.workers.keys()) { - this.unwatch(libraryId); - } - } - - // 获取监控状态 - isWatching(libraryId) { - return this.workers.has(libraryId); - } - - // 获取所有正在监控的库 - getWatchedLibraries() { - return Array.from(this.workers.keys()); - } -} - -// 单例模式 -const fileWatcher = new FileWatcher(); - -module.exports = fileWatcher; diff --git a/flypic/app/server/utils/fileWatcherWorker.js b/flypic/app/server/utils/fileWatcherWorker.js deleted file mode 100644 index 776ed73..0000000 --- a/flypic/app/server/utils/fileWatcherWorker.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * File Watcher Worker - 在独立线程中运行 chokidar - * 避免文件监控初始化阻塞主线程的事件循环 - */ -const { parentPort, workerData } = require('worker_threads'); -const chokidar = require('chokidar'); - -const { libraryPath, libraryName } = workerData; - -console.log(`[Worker] Starting chokidar for: ${libraryName}`); - -// 创建监控器 -const watcher = chokidar.watch(['**/*.*', '**/'], { - cwd: libraryPath, - ignored: [ - '**/node_modules/**', - '**/.git/**', - '**/.flypic/**', - '**/.*' - ], - persistent: true, - ignoreInitial: true, - usePolling: false, - awaitWriteFinish: { - stabilityThreshold: 1000, - pollInterval: 200 - } -}); - -// 监听事件并发送到主线程 -watcher - .on('add', (filePath) => { - parentPort.postMessage({ type: 'add', path: filePath }); - }) - .on('unlink', (filePath) => { - parentPort.postMessage({ type: 'unlink', path: filePath }); - }) - .on('change', (filePath) => { - parentPort.postMessage({ type: 'change', path: filePath }); - }) - .on('addDir', (dirPath) => { - parentPort.postMessage({ type: 'addDir', path: dirPath }); - }) - .on('unlinkDir', (dirPath) => { - parentPort.postMessage({ type: 'unlinkDir', path: dirPath }); - }) - .on('error', (error) => { - parentPort.postMessage({ type: 'error', message: error.message }); - }) - .on('ready', () => { - console.log(`[Worker] File watcher ready for: ${libraryName}`); - parentPort.postMessage({ type: 'ready' }); - }); - -// 监听主线程的关闭命令 -parentPort.on('message', (msg) => { - if (msg.type === 'close') { - console.log(`[Worker] Closing watcher for: ${libraryName}`); - watcher.close().then(() => { - parentPort.postMessage({ type: 'closed' }); - process.exit(0); - }); - } -}); diff --git a/flypic/app/server/utils/lightweightWatcher.js b/flypic/app/server/utils/lightweightWatcher.js new file mode 100644 index 0000000..1fa565b --- /dev/null +++ b/flypic/app/server/utils/lightweightWatcher.js @@ -0,0 +1,402 @@ +/** + * 轻量级文件监控器 + * 使用智能轮询代替 chokidar,内存占用 < 50MB + * + * 策略: + * 1. 每 5-10 秒检查一次文件夹的修改时间戳 + * 2. 只扫描时间戳变化的文件夹 + * 3. 不缓存任何文件元数据 + * 4. 使用增量对比,只处理变化的文件 + */ + +const fs = require('fs').promises; +const path = require('path'); +const { applyChangesFromEvents } = require('./scanner'); +const dbPool = require('../database/dbPool'); + +class LightweightWatcher { + constructor() { + this.watchers = new Map(); // libraryId -> { interval, folderTimestamps, libraryPath } + this.ioRef = null; + this.pollInterval = 5000; // 5 秒轮询一次 + } + + /** + * 启动轻量级监控 + */ + async watch(libraryId, libraryPath, libraryName, io) { + this.ioRef = io; + + // 如果已经在监控,先停止 + if (this.watchers.has(libraryId)) { + this.unwatch(libraryId); + } + + console.log(`[LightweightWatcher] Starting for: ${libraryName}`); + console.log(` Strategy: Folder timestamp polling (${this.pollInterval}ms interval)`); + console.log(` Memory: < 50MB (vs chokidar ~800MB)`); + + // 🔍 检测离线期间的变化 + console.log(`[LightweightWatcher] Checking offline changes...`); + try { + await this._checkOfflineChanges(libraryId, libraryPath, libraryName); + } catch (error) { + console.error(`[LightweightWatcher] Failed to check offline changes:`, error.message); + } + + // 初始化文件夹时间戳缓存 + const folderTimestamps = new Map(); + + try { + await this._initializeFolderTimestamps(libraryPath, folderTimestamps); + console.log(` Initialized ${folderTimestamps.size} folders`); + } catch (error) { + console.error(`[LightweightWatcher] Failed to initialize:`, error.message); + return; + } + + // 启动轮询 + const interval = setInterval(async () => { + try { + await this._checkForChanges(libraryId, libraryPath, libraryName, folderTimestamps); + } catch (error) { + console.error(`[LightweightWatcher] Error checking changes:`, error.message); + } + }, this.pollInterval); + + this.watchers.set(libraryId, { + interval, + folderTimestamps, + libraryPath, + libraryName + }); + + console.log(`[LightweightWatcher] Started for: ${libraryName}`); + } + + /** + * 初始化文件夹时间戳(只扫描文件夹,不扫描文件) + */ + async _initializeFolderTimestamps(libraryPath, folderTimestamps) { + const folders = await this._getAllFolders(libraryPath); + + for (const folder of folders) { + try { + const stats = await fs.stat(folder); + folderTimestamps.set(folder, stats.mtimeMs); + } catch (error) { + // 忽略无法访问的文件夹 + } + } + } + + /** + * 递归获取所有文件夹(不包含文件) + */ + async _getAllFolders(dir, folders = []) { + try { + const entries = await fs.readdir(dir, { withFileTypes: true }); + + for (const entry of entries) { + // 跳过隐藏文件夹和特殊文件夹 + if (entry.name.startsWith('.') || + entry.name === 'node_modules' || + entry.name === '.flypic') { + continue; + } + + if (entry.isDirectory()) { + const fullPath = path.join(dir, entry.name); + folders.push(fullPath); + // 递归获取子文件夹 + await this._getAllFolders(fullPath, folders); + } + } + } catch (error) { + // 忽略无法访问的文件夹 + } + + return folders; + } + + /** + * 检查文件夹变化(核心逻辑) + */ + async _checkForChanges(libraryId, libraryPath, libraryName, folderTimestamps) { + const changedFolders = []; + const deletedFolders = []; + + // 1. 检查现有文件夹的时间戳 + for (const [folder, oldTimestamp] of folderTimestamps.entries()) { + try { + const stats = await fs.stat(folder); + const newTimestamp = stats.mtimeMs; + + if (newTimestamp !== oldTimestamp) { + changedFolders.push(folder); + folderTimestamps.set(folder, newTimestamp); + } + } catch (error) { + // 文件夹被删除 + console.log(`[LightweightWatcher] Folder deleted: ${folder}`); + deletedFolders.push(folder); + folderTimestamps.delete(folder); + } + } + + // 2. 检查新增的文件夹 + const currentFolders = await this._getAllFolders(libraryPath); + for (const folder of currentFolders) { + if (!folderTimestamps.has(folder)) { + console.log(`[LightweightWatcher] New folder detected: ${folder}`); + changedFolders.push(folder); + try { + const stats = await fs.stat(folder); + folderTimestamps.set(folder, stats.mtimeMs); + } catch (error) { + // 忽略 + } + } + } + + // 3. 如果有变化,扫描这些文件夹 + if (changedFolders.length > 0) { + console.log(`[LightweightWatcher] Detected changes in ${changedFolders.length} folders`); + await this._processChangedFolders(libraryId, libraryPath, libraryName, changedFolders); + } + + // 4. 处理删除的文件夹 + if (deletedFolders.length > 0) { + console.log(`[LightweightWatcher] Processing ${deletedFolders.length} deleted folders`); + await this._processDeletedFolders(libraryId, libraryPath, deletedFolders); + } + } + + /** + * 处理变化的文件夹(只扫描这些文件夹) + */ + async _processChangedFolders(libraryId, libraryPath, libraryName, changedFolders) { + const db = dbPool.acquire(libraryPath); // 这是 LibraryDatabase 实例 + + try { + // 获取数据库中这些文件夹的文件列表 + const dbFiles = new Set(); + for (const folder of changedFolders) { + const relativePath = path.relative(libraryPath, folder).replace(/\\/g, '/'); + // 使用正确的 SQL 模式匹配 + const pattern = relativePath ? `${relativePath}/%` : '%'; + const stmt = db.db.prepare('SELECT path FROM images WHERE folder = ? OR folder LIKE ?'); + const rows = stmt.all(relativePath, pattern); + rows.forEach(row => dbFiles.add(row.path)); + } + + // 扫描文件系统中这些文件夹的文件 + const fsFiles = new Set(); + for (const folder of changedFolders) { + await this._scanFolder(folder, libraryPath, fsFiles); + } + + // 对比找出变化 + const filesAdded = []; + const filesRemoved = []; + + for (const file of fsFiles) { + if (!dbFiles.has(file)) { + filesAdded.push(file); + } + } + + for (const file of dbFiles) { + if (!fsFiles.has(file)) { + filesRemoved.push(file); + } + } + + // 应用变化 + if (filesAdded.length > 0 || filesRemoved.length > 0) { + console.log(`[LightweightWatcher] Changes: +${filesAdded.length} -${filesRemoved.length}`); + + // 打印详细信息用于调试 + if (filesAdded.length > 0) { + console.log(`[LightweightWatcher] Files added:`, filesAdded.slice(0, 5)); + } + if (filesRemoved.length > 0) { + console.log(`[LightweightWatcher] Files removed:`, filesRemoved.slice(0, 5)); + } + + const results = await applyChangesFromEvents(libraryPath, db, { + filesAdded, + filesChanged: [], + filesRemoved, + dirsAdded: [], + dirsRemoved: [] + }); + + if (this.ioRef) { + console.log(`[LightweightWatcher] Emitting scanComplete event for library ${libraryId}`); + this.ioRef.emit('scanComplete', { libraryId, results }); + } else { + console.warn(`[LightweightWatcher] No Socket.IO reference, cannot emit scanComplete`); + } + } + } catch (error) { + console.error(`[LightweightWatcher] Error processing changes:`, error); + if (this.ioRef) { + this.ioRef.emit('scanError', { libraryId, error: error.message }); + } + } finally { + dbPool.release(libraryPath); + } + } + + /** + * 扫描单个文件夹的所有支持的文件 + */ + async _scanFolder(folder, libraryPath, fsFiles) { + try { + const entries = await fs.readdir(folder, { withFileTypes: true }); + // 支持所有文件类型(与 scanner.js 保持一致) + const supportedExtensions = [ + // 图片 + '.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg', '.tiff', '.tif', '.avif', '.heif', '.heic', + // 视频 + '.mp4', '.webm', '.mov', '.avi', '.mkv', '.flv', '.m4v', '.wmv', '.mpg', '.mpeg', + // 音频 + '.mp3', '.wav', '.flac', '.aac', '.m4a', '.ogg', + // 文档 + '.pdf', '.txt', '.md', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', + // 设计 + '.psd', '.ai', '.sketch', '.xd', '.fig' + ]; + + for (const entry of entries) { + if (entry.isFile()) { + const ext = path.extname(entry.name).toLowerCase(); + if (supportedExtensions.includes(ext)) { + const fullPath = path.join(folder, entry.name); + const relativePath = path.relative(libraryPath, fullPath).replace(/\\/g, '/'); + fsFiles.add(relativePath); + } + } + } + } catch (error) { + // 忽略无法访问的文件夹 + console.warn(`[LightweightWatcher] Cannot access folder: ${folder}`, error.message); + } + } + + /** + * 处理删除的文件夹 + */ + async _processDeletedFolders(libraryId, libraryPath, deletedFolders) { + const db = dbPool.acquire(libraryPath); + + try { + const filesRemoved = []; + + // 获取这些文件夹中的所有文件 + for (const folder of deletedFolders) { + const relativePath = path.relative(libraryPath, folder); + const stmt = db.db.prepare('SELECT path FROM images WHERE path LIKE ?'); + const rows = stmt.all(`${relativePath}%`); + rows.forEach(row => filesRemoved.push(row.path)); + } + + if (filesRemoved.length > 0) { + console.log(`[LightweightWatcher] Removing ${filesRemoved.length} files from deleted folders`); + + const results = await applyChangesFromEvents(libraryPath, db, { + filesAdded: [], + filesChanged: [], + filesRemoved, + dirsAdded: [], + dirsRemoved: deletedFolders.map(f => path.relative(libraryPath, f)) + }); + + if (this.ioRef) { + this.ioRef.emit('scanComplete', { libraryId, results }); + } + } + } catch (error) { + console.error(`[LightweightWatcher] Error processing deleted folders:`, error); + } finally { + dbPool.release(libraryPath); + } + } + + /** + * 停止监控 + */ + unwatch(libraryId) { + const watcher = this.watchers.get(libraryId); + if (watcher) { + clearInterval(watcher.interval); + this.watchers.delete(libraryId); + console.log(`[LightweightWatcher] Stopped for: ${watcher.libraryName}`); + } + } + + /** + * 检测离线期间的变化 + * 使用 quickSync 快速检测新增和删除的文件 + */ + async _checkOfflineChanges(libraryId, libraryPath, libraryName) { + const db = dbPool.acquire(libraryPath); + + try { + const { quickSync } = require('./scanner'); + + // 使用 quickSync 快速检测变化(只检查新增/删除,不检查修改) + const results = await quickSync(libraryPath, db); + + const changes = results.added + results.deleted; + if (changes > 0) { + console.log(`[LightweightWatcher] Offline changes: +${results.added} -${results.deleted}`); + + // 发送完成事件 + if (this.ioRef) { + this.ioRef.emit('scanComplete', { libraryId, results }); + } + } else { + console.log(`[LightweightWatcher] No offline changes`); + } + } catch (error) { + console.error(`[LightweightWatcher] Error checking offline changes:`, error); + } finally { + dbPool.release(libraryPath); + } + } + + /** + * 停止所有监控 + */ + stopAll() { + for (const libraryId of this.watchers.keys()) { + this.unwatch(libraryId); + } + } + + // 别名,保持兼容性 + unwatchAll() { + this.stopAll(); + } + + /** + * 获取监控状态 + */ + isWatching(libraryId) { + return this.watchers.has(libraryId); + } + + /** + * 获取所有正在监控的库 + */ + getWatchedLibraries() { + return Array.from(this.watchers.keys()); + } +} + +// 单例模式 +const lightweightWatcher = new LightweightWatcher(); + +module.exports = lightweightWatcher; diff --git a/flypic/app/server/utils/memoryDiagnostics.js b/flypic/app/server/utils/memoryDiagnostics.js new file mode 100644 index 0000000..b6b7280 --- /dev/null +++ b/flypic/app/server/utils/memoryDiagnostics.js @@ -0,0 +1,176 @@ +/** + * Memory Diagnostics Tool + * 诊断内存泄漏和高内存使用 + */ + +const v8 = require('v8'); +const fs = require('fs'); +const path = require('path'); + +/** + * 生成堆快照 + */ +function takeHeapSnapshot(filename) { + const snapshotPath = path.join(__dirname, '..', 'logs', filename); + + // 确保目录存在 + const dir = path.dirname(snapshotPath); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } + + const snapshot = v8.writeHeapSnapshot(snapshotPath); + console.log(`[MemoryDiagnostics] Heap snapshot saved: ${snapshot}`); + return snapshot; +} + +/** + * 获取堆统计信息 + */ +function getHeapStatistics() { + const stats = v8.getHeapStatistics(); + return { + totalHeapSize: (stats.total_heap_size / 1024 / 1024).toFixed(2) + ' MB', + totalHeapSizeExecutable: (stats.total_heap_size_executable / 1024 / 1024).toFixed(2) + ' MB', + totalPhysicalSize: (stats.total_physical_size / 1024 / 1024).toFixed(2) + ' MB', + totalAvailableSize: (stats.total_available_size / 1024 / 1024).toFixed(2) + ' MB', + usedHeapSize: (stats.used_heap_size / 1024 / 1024).toFixed(2) + ' MB', + heapSizeLimit: (stats.heap_size_limit / 1024 / 1024).toFixed(2) + ' MB', + mallocedMemory: (stats.malloced_memory / 1024 / 1024).toFixed(2) + ' MB', + peakMallocedMemory: (stats.peak_malloced_memory / 1024 / 1024).toFixed(2) + ' MB', + doesZapGarbage: stats.does_zap_garbage + }; +} + +/** + * 打印堆统计信息 + */ +function logHeapStatistics() { + const stats = getHeapStatistics(); + console.log('\n[MemoryDiagnostics] Heap Statistics:'); + Object.entries(stats).forEach(([key, value]) => { + console.log(` ${key}: ${value}`); + }); +} + +/** + * 强制垃圾回收并报告 + */ +function forceGCAndReport() { + if (!global.gc) { + console.warn('[MemoryDiagnostics] GC not available. Run with --expose-gc'); + return null; + } + + const before = process.memoryUsage(); + const beforeRSS = before.rss / 1024 / 1024; + const beforeHeap = before.heapUsed / 1024 / 1024; + + console.log(`[MemoryDiagnostics] Before GC: RSS=${beforeRSS.toFixed(0)}MB, Heap=${beforeHeap.toFixed(0)}MB`); + + // 执行多次 GC + for (let i = 0; i < 5; i++) { + global.gc(); + } + + const after = process.memoryUsage(); + const afterRSS = after.rss / 1024 / 1024; + const afterHeap = after.heapUsed / 1024 / 1024; + + const rssReclaimed = beforeRSS - afterRSS; + const heapReclaimed = beforeHeap - afterHeap; + + console.log(`[MemoryDiagnostics] After GC: RSS=${afterRSS.toFixed(0)}MB, Heap=${afterHeap.toFixed(0)}MB`); + console.log(`[MemoryDiagnostics] Reclaimed: RSS=${rssReclaimed.toFixed(0)}MB, Heap=${heapReclaimed.toFixed(0)}MB`); + + return { + before: { rss: beforeRSS, heap: beforeHeap }, + after: { rss: afterRSS, heap: afterHeap }, + reclaimed: { rss: rssReclaimed, heap: heapReclaimed } + }; +} + +/** + * 检测可能的内存泄漏 + */ +function detectMemoryLeak() { + const usage = process.memoryUsage(); + const rss = usage.rss / 1024 / 1024; + const heap = usage.heapUsed / 1024 / 1024; + const external = usage.external / 1024 / 1024; + + const issues = []; + + // RSS 过高 + if (rss > 500) { + issues.push({ + type: 'HIGH_RSS', + severity: 'critical', + message: `RSS is very high: ${rss.toFixed(0)}MB`, + suggestion: 'Check for native memory leaks, large buffers, or file handles' + }); + } + + // Heap 过高 + if (heap > 200) { + issues.push({ + type: 'HIGH_HEAP', + severity: 'warning', + message: `Heap usage is high: ${heap.toFixed(0)}MB`, + suggestion: 'Check for object retention, closures, or large data structures' + }); + } + + // External 过高 + if (external > 100) { + issues.push({ + type: 'HIGH_EXTERNAL', + severity: 'warning', + message: `External memory is high: ${external.toFixed(0)}MB`, + suggestion: 'Check for Buffer allocations, native addons, or C++ objects' + }); + } + + // RSS 远大于 Heap(可能是 native 内存泄漏) + if (rss > heap * 3) { + issues.push({ + type: 'RSS_HEAP_MISMATCH', + severity: 'critical', + message: `RSS (${rss.toFixed(0)}MB) is much larger than Heap (${heap.toFixed(0)}MB)`, + suggestion: 'Likely native memory leak. Check SQLite, Sharp, or other native modules' + }); + } + + return issues; +} + +/** + * 打印内存泄漏诊断 + */ +function diagnoseMemoryLeak() { + console.log('\n[MemoryDiagnostics] Running memory leak detection...\n'); + + const issues = detectMemoryLeak(); + + if (issues.length === 0) { + console.log('✅ No obvious memory issues detected'); + } else { + console.log(`⚠️ Found ${issues.length} potential issues:\n`); + issues.forEach((issue, index) => { + console.log(`${index + 1}. [${issue.severity.toUpperCase()}] ${issue.type}`); + console.log(` ${issue.message}`); + console.log(` 💡 ${issue.suggestion}\n`); + }); + } + + return issues; +} + +module.exports = { + takeHeapSnapshot, + getHeapStatistics, + logHeapStatistics, + forceGCAndReport, + detectMemoryLeak, + diagnoseMemoryLeak +}; diff --git a/flypic/app/server/utils/memoryMonitor.js b/flypic/app/server/utils/memoryMonitor.js new file mode 100644 index 0000000..1b89ec5 --- /dev/null +++ b/flypic/app/server/utils/memoryMonitor.js @@ -0,0 +1,195 @@ +/** + * Memory Monitor + * Continuously monitors memory usage and triggers cleanup when thresholds are exceeded + */ + +class MemoryMonitor { + constructor(options = {}) { + this.warningThreshold = options.warningThreshold || 150 * 1024 * 1024; // 150MB + this.dangerThreshold = options.dangerThreshold || 300 * 1024 * 1024; // 300MB + this.checkInterval = options.checkInterval || 2000; // 2 seconds + this.cleanupManager = options.cleanupManager; + this.devMode = options.devMode || process.env.NODE_ENV === 'development'; + this.devLogInterval = options.devLogInterval || 30000; // 30 seconds + + this.intervalId = null; + this.devLogIntervalId = null; + this.isRunning = false; + this.lastWarningTime = 0; + this.lastDangerTime = 0; + this.warningCooldown = 10000; // 10 seconds between warnings + } + + /** + * Start monitoring memory usage + */ + start() { + if (this.isRunning) return; + + console.log('📊 内存监控已启动'); + + this.isRunning = true; + + // Start periodic memory checks + this.intervalId = setInterval(() => { + this.checkMemory(); + }, this.checkInterval); + + // Start development mode logging + if (this.devMode) { + this.devLogIntervalId = setInterval(() => { + const stats = this.getMemoryStats(); + this.logMemoryStats(stats, 'DEV'); + }, this.devLogInterval); + } + + // Initial check + this.checkMemory(); + } + + /** + * Stop monitoring + */ + stop() { + if (!this.isRunning) return; + + console.log('📊 内存监控已停止'); + + if (this.intervalId) { + clearInterval(this.intervalId); + this.intervalId = null; + } + + if (this.devLogIntervalId) { + clearInterval(this.devLogIntervalId); + this.devLogIntervalId = null; + } + + this.isRunning = false; + } + + /** + * Get current memory statistics + * @returns {Object} Memory statistics + */ + getMemoryStats() { + const usage = process.memoryUsage(); + return { + heapUsed: usage.heapUsed, + heapTotal: usage.heapTotal, + rss: usage.rss, + external: usage.external, + arrayBuffers: usage.arrayBuffers, + timestamp: Date.now() + }; + } + + /** + * Check memory and trigger actions if thresholds exceeded + */ + checkMemory() { + const stats = this.getMemoryStats(); + const heapUsedMB = stats.heapUsed / 1024 / 1024; + + // Check danger threshold first + if (stats.heapUsed > this.dangerThreshold) { + this.handleDanger(stats); + } + // Check warning threshold + else if (stats.heapUsed > this.warningThreshold) { + this.handleWarning(stats); + } + + return stats; + } + + /** + * Handle warning threshold exceeded + */ + handleWarning(stats) { + const now = Date.now(); + + // Cooldown to avoid spam + if (now - this.lastWarningTime < this.warningCooldown) { + return; + } + + this.lastWarningTime = now; + + console.warn('⚠️ 内存使用偏高'); + this.logMemoryStats(stats, 'WARNING'); + } + + /** + * Handle danger threshold exceeded + */ + handleDanger(stats) { + const now = Date.now(); + + // Cooldown to avoid spam (shorter for danger) + if (now - this.lastDangerTime < 5000) { + return; + } + + this.lastDangerTime = now; + + console.error('🚨 内存使用危险!'); + this.logMemoryStats(stats, 'DANGER'); + + // Trigger emergency cleanup if cleanup manager is available + if (this.cleanupManager) { + console.log('🚨 触发紧急清理...'); + try { + this.cleanupManager.executeEmergencyCleanup(); + + // 等待一下再检查 + setTimeout(() => { + const afterStats = this.getMemoryStats(); + const afterRSS = afterStats.rss / 1024 / 1024; + + // 如果 RSS 仍然很高,强制更多 GC + if (afterRSS > 500) { + if (global.gc) { + for (let i = 0; i < 10; i++) { + global.gc(); + } + } + } + }, 1000); + } catch (error) { + console.error('❌ 紧急清理失败:', error.message); + } + } + } + + /** + * Log memory statistics with detailed breakdown + */ + logMemoryStats(stats, level = 'INFO') { + const heapUsedMB = (stats.heapUsed / 1024 / 1024).toFixed(2); + const heapTotalMB = (stats.heapTotal / 1024 / 1024).toFixed(2); + const rssMB = (stats.rss / 1024 / 1024).toFixed(2); + const externalMB = (stats.external / 1024 / 1024).toFixed(2); + const arrayBuffersMB = (stats.arrayBuffers / 1024 / 1024).toFixed(2); + + console.log(`📊 内存状态 [${level}]:`); + console.log(` Heap: ${heapUsedMB}/${heapTotalMB} MB`); + console.log(` RSS: ${rssMB} MB`); + console.log(` External: ${externalMB} MB`); + } + + /** + * Get monitoring status + */ + getStatus() { + return { + isRunning: this.isRunning, + warningThreshold: this.warningThreshold, + dangerThreshold: this.dangerThreshold, + checkInterval: this.checkInterval, + currentMemory: this.isRunning ? this.getMemoryStats() : null + }; + } +} + +module.exports = MemoryMonitor; diff --git a/flypic/app/server/utils/memoryStats.js b/flypic/app/server/utils/memoryStats.js new file mode 100644 index 0000000..9806815 --- /dev/null +++ b/flypic/app/server/utils/memoryStats.js @@ -0,0 +1,63 @@ +/** + * Memory Statistics Utility + * 显示详细的内存使用统计 + */ + +function formatBytes(bytes) { + return (bytes / 1024 / 1024).toFixed(2) + ' MB'; +} + +function getMemoryStats() { + const usage = process.memoryUsage(); + + return { + heapUsed: usage.heapUsed, + heapTotal: usage.heapTotal, + rss: usage.rss, + external: usage.external, + arrayBuffers: usage.arrayBuffers, + heapUsedMB: formatBytes(usage.heapUsed), + heapTotalMB: formatBytes(usage.heapTotal), + rssMB: formatBytes(usage.rss), + externalMB: formatBytes(usage.external), + arrayBuffersMB: formatBytes(usage.arrayBuffers) + }; +} + +function logMemoryStats(label = 'Memory') { + const stats = getMemoryStats(); + console.log(`\n[${label}] Memory Statistics:`); + console.log(` RSS (总内存): ${stats.rssMB}`); + console.log(` Heap Used (堆使用): ${stats.heapUsedMB}`); + console.log(` Heap Total (堆总量):${stats.heapTotalMB}`); + console.log(` External (外部): ${stats.externalMB}`); + console.log(` Array Buffers: ${stats.arrayBuffersMB}`); +} + +function getMemoryPressure() { + const usage = process.memoryUsage(); + const heapUsedMB = usage.heapUsed / 1024 / 1024; + const rssMB = usage.rss / 1024 / 1024; + + let pressure = 'low'; + if (heapUsedMB > 200 || rssMB > 500) { + pressure = 'critical'; + } else if (heapUsedMB > 100 || rssMB > 300) { + pressure = 'high'; + } else if (heapUsedMB > 50 || rssMB > 150) { + pressure = 'medium'; + } + + return { + level: pressure, + heapUsedMB, + rssMB + }; +} + +module.exports = { + getMemoryStats, + logMemoryStats, + getMemoryPressure, + formatBytes +}; diff --git a/flypic/app/server/utils/migrateThumbnails.js b/flypic/app/server/utils/migrateThumbnails.js new file mode 100644 index 0000000..bde2671 --- /dev/null +++ b/flypic/app/server/utils/migrateThumbnails.js @@ -0,0 +1,148 @@ +/** + * 缩略图迁移工具 + * 将旧结构的缩略图迁移到新的分片结构 + * + * 旧结构:.flypic/thumbnails/hash.webp + * 新结构:.flypic/thumbnails/ab/hash.webp (分片存储) + */ + +const fs = require('fs'); +const path = require('path'); + +/** + * 迁移单个素材库的缩略图 + * @param {string} libraryPath - 素材库路径 + * @returns {Object} 迁移结果统计 + */ +async function migrateThumbnails(libraryPath) { + const thumbnailsDir = path.join(libraryPath, '.flypic', 'thumbnails'); + + // 检查目录是否存在 + if (!fs.existsSync(thumbnailsDir)) { + return { migrated: 0, skipped: 0, errors: 0, message: 'Thumbnails directory not found' }; + } + + const stats = { + migrated: 0, + skipped: 0, + errors: 0 + }; + + try { + const entries = fs.readdirSync(thumbnailsDir, { withFileTypes: true }); + + for (const entry of entries) { + // 跳过已经是目录的(已经是新结构) + if (entry.isDirectory()) { + continue; + } + + // 只处理 .webp 文件 + if (!entry.name.endsWith('.webp')) { + continue; + } + + try { + const oldPath = path.join(thumbnailsDir, entry.name); + + // 提取 hash(去掉扩展名) + const hash = entry.name.replace('.webp', ''); + + // 计算分片目录(使用前2个字符) + const shard = hash.slice(0, 2); + const shardDir = path.join(thumbnailsDir, shard); + const newPath = path.join(shardDir, entry.name); + + // 如果新路径已存在,跳过 + if (fs.existsSync(newPath)) { + stats.skipped++; + continue; + } + + // 创建分片目录 + if (!fs.existsSync(shardDir)) { + fs.mkdirSync(shardDir, { recursive: true }); + } + + // 移动文件 + fs.renameSync(oldPath, newPath); + stats.migrated++; + + console.log(`[Migrate] Moved: ${entry.name} -> ${shard}/${entry.name}`); + } catch (error) { + console.error(`[Migrate] Error migrating ${entry.name}:`, error.message); + stats.errors++; + } + } + + console.log(`[Migrate] Complete for ${libraryPath}:`, stats); + return stats; + } catch (error) { + console.error(`[Migrate] Error reading thumbnails directory:`, error); + return { ...stats, message: error.message }; + } +} + +/** + * 检查是否需要迁移 + * @param {string} libraryPath - 素材库路径 + * @returns {boolean} 是否需要迁移 + */ +function needsMigration(libraryPath) { + const thumbnailsDir = path.join(libraryPath, '.flypic', 'thumbnails'); + + if (!fs.existsSync(thumbnailsDir)) { + return false; + } + + try { + const entries = fs.readdirSync(thumbnailsDir, { withFileTypes: true }); + + // 检查是否有直接在 thumbnails 目录下的 .webp 文件 + for (const entry of entries) { + if (entry.isFile() && entry.name.endsWith('.webp')) { + return true; + } + } + + return false; + } catch (error) { + console.error(`[Migrate] Error checking migration need:`, error); + return false; + } +} + +/** + * 批量迁移多个素材库 + * @param {Array} libraries - 素材库列表 + * @returns {Object} 总体迁移统计 + */ +async function migrateAllLibraries(libraries) { + const totalStats = { + migrated: 0, + skipped: 0, + errors: 0, + librariesProcessed: 0 + }; + + for (const library of libraries) { + if (needsMigration(library.path)) { + console.log(`[Migrate] Processing library: ${library.name}`); + const stats = await migrateThumbnails(library.path); + + totalStats.migrated += stats.migrated; + totalStats.skipped += stats.skipped; + totalStats.errors += stats.errors; + totalStats.librariesProcessed++; + } + } + + console.log(`[Migrate] Total stats:`, totalStats); + return totalStats; +} + +module.exports = { + migrateThumbnails, + needsMigration, + migrateAllLibraries +}; diff --git a/flypic/app/server/utils/scanManager.js b/flypic/app/server/utils/scanManager.js index e251e5e..b35dee1 100644 --- a/flypic/app/server/utils/scanManager.js +++ b/flypic/app/server/utils/scanManager.js @@ -1,6 +1,6 @@ /** - * 扫描状态管理器 - * 支持扫描的停止、继续和持久化 + * 扫描状态管理器(简化版) + * 只负责进度持久化,无暂停功能 */ const fs = require('fs'); @@ -8,17 +8,17 @@ const path = require('path'); class ScanManager { constructor() { - // 每个素材库的扫描状态(内存) this.scanStates = new Map(); - // 素材库路径映射(用于持久化) this.libraryPaths = new Map(); + this.saveTimers = new Map(); } /** - * 注册素材库路径(用于持久化) + * 注册素材库路径 */ registerLibraryPath(libraryId, libraryPath) { this.libraryPaths.set(libraryId, libraryPath); + this._restoreStateFromFile(libraryId); } /** @@ -31,15 +31,15 @@ class ScanManager { } /** - * 保存状态到文件(轻量:只保存关键信息) + * 保存状态到文件 */ saveState(libraryId) { const stateFile = this.getStateFilePath(libraryId); if (!stateFile) return; const state = this.scanStates.get(libraryId); + if (!state || state.status === 'idle') { - // 删除状态文件 try { if (fs.existsSync(stateFile)) { fs.unlinkSync(stateFile); @@ -49,19 +49,38 @@ class ScanManager { } try { + const dir = path.dirname(stateFile); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } + const saveData = { status: state.status, progress: state.progress, - pendingCount: state.pendingFiles?.length || 0, - // 只保存文件相对路径,不保存完整路径列表(太大) + startTime: state.startTime, savedAt: Date.now() }; + fs.writeFileSync(stateFile, JSON.stringify(saveData, null, 2)); } catch (e) { - console.error('Failed to save scan state:', e.message); + console.error('❌ 保存扫描状态失败:', e.message); } } + /** + * 定时保存(每5秒) + */ + _scheduleSave(libraryId) { + if (this.saveTimers.has(libraryId)) { + clearTimeout(this.saveTimers.get(libraryId)); + } + const timer = setTimeout(() => { + this.saveState(libraryId); + this.saveTimers.delete(libraryId); + }, 5000); + this.saveTimers.set(libraryId, timer); + } + /** * 从文件加载状态 */ @@ -71,7 +90,7 @@ class ScanManager { try { const data = JSON.parse(fs.readFileSync(stateFile, 'utf8')); - // 状态超过 24 小时视为过期 + // 24小时过期 if (Date.now() - data.savedAt > 24 * 60 * 60 * 1000) { fs.unlinkSync(stateFile); return null; @@ -83,48 +102,67 @@ class ScanManager { } /** - * 获取扫描状态(优先内存,其次文件) + * 从文件恢复状态 + */ + _restoreStateFromFile(libraryId) { + if (this.scanStates.has(libraryId)) { + return; + } + + const fileState = this.loadState(libraryId); + + if (fileState && fileState.status === 'scanning') { + this.scanStates.set(libraryId, { + status: fileState.status, + progress: fileState.progress, + startTime: fileState.startTime + }); + console.log(`🔄 恢复扫描状态: ${fileState.progress?.percent || 0}%`); + } + } + + /** + * 获取扫描状态 */ getState(libraryId) { - // 先检查内存中的状态 const memState = this.scanStates.get(libraryId); if (memState) return memState; - // 尝试从文件加载(应用重启后的恢复) const fileState = this.loadState(libraryId); - if (fileState && fileState.status === 'paused') { - // 重建内存状态(不含 pendingFiles,需要重新扫描确定) + if (fileState && fileState.status === 'scanning') { const restored = { - status: 'paused', + status: 'scanning', progress: fileState.progress, - pendingFiles: [], // 无法恢复完整列表,需要继续扫描时重新计算 - processedCount: fileState.progress?.current || 0, - abortController: { aborted: true }, - needsRescan: true // 标记需要重新扫描 + startTime: fileState.startTime }; this.scanStates.set(libraryId, restored); return restored; } - return { - status: 'idle', - progress: null, - pendingFiles: [], - processedCount: 0 - }; + return { status: 'idle', progress: null }; } /** * 开始扫描 */ - startScan(libraryId, totalFiles) { + startScan(libraryId, totalFiles, libraryPath) { + // 确保路径已注册 + if (libraryPath && !this.libraryPaths.has(libraryId)) { + this.libraryPaths.set(libraryId, libraryPath); + } + + if (this.saveTimers.has(libraryId)) { + clearTimeout(this.saveTimers.get(libraryId)); + this.saveTimers.delete(libraryId); + } + this.scanStates.set(libraryId, { status: 'scanning', progress: { current: 0, total: totalFiles, percent: 0 }, - pendingFiles: [], - processedCount: 0, - abortController: { aborted: false } + startTime: Date.now() }); + + this.saveState(libraryId); return this.scanStates.get(libraryId); } @@ -139,68 +177,15 @@ class ScanManager { total, percent: Math.round((current / total) * 100) }; - state.processedCount = current; + this._scheduleSave(libraryId); } } - /** - * 停止扫描 - */ - stopScan(libraryId, pendingFiles = []) { - const state = this.scanStates.get(libraryId); - if (state) { - state.status = 'paused'; - state.pendingFiles = pendingFiles; - state.abortController.aborted = true; - // 持久化状态 - this.saveState(libraryId); - console.log(`⏸️ Scan paused for ${libraryId}, ${pendingFiles.length} files pending`); - } - } - - /** - * 检查是否应该停止 - */ - shouldStop(libraryId) { - const state = this.scanStates.get(libraryId); - return state?.abortController?.aborted || false; - } - - /** - * 获取待处理文件 - */ - getPendingFiles(libraryId) { - const state = this.scanStates.get(libraryId); - return state?.pendingFiles || []; - } - - /** - * 恢复扫描 - */ - resumeScan(libraryId) { - const state = this.scanStates.get(libraryId); - if (state && state.status === 'paused') { - const pendingFiles = [...state.pendingFiles]; // 复制一份 - state.status = 'scanning'; - state.abortController = { aborted: false }; - state.pendingFiles = []; // 清空待处理列表 - console.log(`▶️ Scan resumed for ${libraryId}, ${pendingFiles.length} files to process`); - return pendingFiles; - } - return []; - } - /** * 完成扫描 */ completeScan(libraryId) { - const state = this.scanStates.get(libraryId); - if (state) { - state.status = 'idle'; - state.pendingFiles = []; - state.progress = null; - } - // 清除持久化状态 + this.scanStates.delete(libraryId); this.saveState(libraryId); } @@ -212,34 +197,50 @@ class ScanManager { return state?.status === 'scanning'; } - /** - * 是否已暂停 - */ - isPaused(libraryId) { - const state = this.scanStates.get(libraryId); - return state?.status === 'paused'; - } - /** * 清除素材库状态(删除素材库时调用) */ clearState(libraryId) { this.scanStates.delete(libraryId); + this.libraryPaths.delete(libraryId); + // 删除状态文件 + const stateFile = this.getStateFilePath(libraryId); + if (stateFile) { + try { + const fs = require('fs'); + if (fs.existsSync(stateFile)) { + fs.unlinkSync(stateFile); + } + } catch (e) { /* ignore */ } + } } /** - * 清除所有空闲状态(内存清理) + * 获取所有活跃状态 */ - cleanupIdleStates() { + getAllActiveStates() { + const activeStates = {}; for (const [libraryId, state] of this.scanStates.entries()) { - if (state.status === 'idle') { - this.scanStates.delete(libraryId); + if (state.status === 'scanning') { + activeStates[libraryId] = { + status: state.status, + progress: state.progress, + startTime: state.startTime + }; } } + return activeStates; + } + + /** + * 恢复所有素材库状态 + */ + restoreAllStates(libraries) { + for (const lib of libraries) { + this.registerLibraryPath(lib.id, lib.path); + } } } -// 单例 const scanManager = new ScanManager(); - module.exports = scanManager; diff --git a/flypic/app/server/utils/scanner.js b/flypic/app/server/utils/scanner.js index 0a66c5b..ec00be1 100644 --- a/flypic/app/server/utils/scanner.js +++ b/flypic/app/server/utils/scanner.js @@ -35,6 +35,13 @@ function ensureFolderChain(db, folderPath) { visited.add(current); const parent = path.posix.dirname(current); const name = current.split('/').pop(); + + // 安全检查:确保 db 对象有 getFolderByPath 方法 + if (typeof db.getFolderByPath !== 'function') { + console.error('❌ db.getFolderByPath 不是函数'); + return; + } + const existing = db.getFolderByPath(current); if (!existing) { db.insertFolder({ @@ -108,7 +115,7 @@ async function applyChangesFromEvents(libraryPath, db, events) { } results.added++; } catch (error) { - console.error(`Error processing added file ${file}:`, error.message); + console.error(`❌ 处理新增文件失败 ${file}:`, error.message); } } @@ -129,7 +136,7 @@ async function applyChangesFromEvents(libraryPath, db, events) { affectedFolders.add(folder); results.modified++; } catch (error) { - console.error(`Error processing changed file ${file}:`, error.message); + console.error(`❌ 处理修改文件失败 ${file}:`, error.message); } } @@ -150,7 +157,7 @@ async function applyChangesFromEvents(libraryPath, db, events) { } results.deleted++; } catch (error) { - console.error(`Error deleting file ${file}:`, error.message); + console.error(`❌ 删除文件失败 ${file}:`, error.message); } } @@ -165,7 +172,7 @@ async function applyChangesFromEvents(libraryPath, db, events) { if (parent && parent !== '.') affectedFolders.add(parent); results.foldersRemoved++; } catch (error) { - console.error(`Error deleting directory ${dir}:`, error.message); + console.error(`❌ 删除目录失败 ${dir}:`, error.message); } } @@ -175,14 +182,14 @@ async function applyChangesFromEvents(libraryPath, db, events) { try { db.updateFolderImageCount(folderPath); } catch (error) { - console.error(`Error updating folder count ${folderPath}:`, error.message); + console.error(`❌ 更新文件夹计数失败 ${folderPath}:`, error.message); } } }); return results; } catch (error) { - console.error('Error in applyChangesFromEvents:', error); + console.error('❌ 应用变化失败:', error.message); throw error; } } @@ -302,7 +309,7 @@ async function processImage(imagePath, libraryPath, db, dryRun = false) { return { status: 'processed', path: relativePath }; } catch (error) { - console.error('Error processing image:', imagePath, error); + console.error('❌ 处理图片失败:', path.basename(imagePath), error.message); return { status: 'error', path: imagePath, error: error.message }; } } @@ -333,20 +340,15 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume // 根据 CPU 核心数动态调整并发数 const os = require('os'); const cpuCount = os.cpus().length; - // 默认并发数:核心数 - 1,最小 4,最大 16 const concurrency = Math.max(4, Math.min(16, cpuCount - 1)); const limit = pLimit(concurrency); - console.log(`🚀 Starting scan with concurrency: ${concurrency} (CPU cores: ${cpuCount})`); - if (resumeFiles && resumeFiles.length > 0) { // 继续扫描:使用待处理文件列表 files = resumeFiles; - console.log(`▶️ Resuming scan with ${files.length} pending files`); } else { // 新扫描:获取所有文件 files = await getAllImageFiles(libraryPath); - console.log(`Found ${files.length} images in library`); // Get folder structure const folders = await getFolderStructure(libraryPath); @@ -361,7 +363,7 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume // 初始化扫描状态 if (libraryId) { - scanManager.startScan(libraryId, total); + scanManager.startScan(libraryId, total, libraryPath); } const results = { @@ -376,7 +378,8 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume // 批量写入缓冲区 let writeBuffer = []; - const WRITE_BATCH_SIZE = 100; // 每 100 条写入一次数据库 + const WRITE_BATCH_SIZE = 50; // 每 50 条写入一次数据库(降低内存峰值) + const STREAM_BATCH_SIZE = 200; // 每批处理 200 个文件(流式处理) // 批量写入函数(事务) const batchWrite = db.db.transaction((items) => { @@ -389,11 +392,6 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume // 处理单个文件的包装函数 const processFile = async (file) => { - // 检查是否需要停止 - if (libraryId && scanManager.shouldStop(libraryId)) { - return { status: 'stopped', file }; - } - try { const result = await processImage(file, libraryPath, db, true); // true = dryRun (不直接写入DB) return result; @@ -402,71 +400,82 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume } }; - // 创建所有任务 - const tasks = files.map(file => limit(async () => { - // 如果已经停止,直接返回 - if (results.stopped) return; + // 流式处理:分批处理文件,避免一次性创建大量 Promise + for (let batchStart = 0; batchStart < total; batchStart += STREAM_BATCH_SIZE) { + const batchEnd = Math.min(batchStart + STREAM_BATCH_SIZE, total); + const batchFiles = files.slice(batchStart, batchEnd); - const result = await processFile(file); + // 处理当前批次 + const batchTasks = batchFiles.map(file => limit(async () => { + const result = await processFile(file); - if (result.status === 'stopped') { - results.stopped = true; - return; - } + // 更新统计 + if (result.status === 'processed') results.processed++; + else if (result.status === 'skipped') results.skipped++; + else if (result.status === 'error') results.errors++; - // 更新统计 - if (result.status === 'processed') results.processed++; - else if (result.status === 'skipped') results.skipped++; - else if (result.status === 'error') results.errors++; + // 添加到写入缓冲区 + if (result.status === 'processed') { + writeBuffer.push(result); - // 添加到写入缓冲区 - if (result.status === 'processed') { - writeBuffer.push(result); - - // 缓冲区满,执行批量写入 - if (writeBuffer.length >= WRITE_BATCH_SIZE) { - batchWrite(writeBuffer); - writeBuffer = []; - } - } - - processedCount++; - - // 报告进度 (每完成 10 个文件报告一次,避免过于频繁) - if (processedCount % 10 === 0 || processedCount === total) { - const current = processedCount; - - if (libraryId) { - scanManager.updateProgress(libraryId, current, total); + // 缓冲区满,执行批量写入 + if (writeBuffer.length >= WRITE_BATCH_SIZE) { + batchWrite(writeBuffer); + writeBuffer = []; // 清空缓冲区,释放内存 + } } - if (onProgress) { - const elapsed = Date.now() - startTime; - const avgTimePerImage = elapsed / current; - const remaining = total - current; - const estimatedTimeLeft = Math.round((remaining * avgTimePerImage) / 1000); + processedCount++; - onProgress({ - total, - current, - percent: Math.round((current / total) * 100), - currentFile: file, - estimatedTimeLeft, - canStop: true - }); + // 报告进度 (每完成 10 个文件报告一次) + if (processedCount % 10 === 0 || processedCount === total) { + const current = processedCount; + + if (libraryId) { + scanManager.updateProgress(libraryId, current, total); + } + + if (onProgress) { + const elapsed = Date.now() - startTime; + const avgTimePerImage = elapsed / current; + const remaining = total - current; + const estimatedTimeLeft = Math.round((remaining * avgTimePerImage) / 1000); + + onProgress({ + total, + current, + percent: Math.round((current / total) * 100), + currentFile: file, + estimatedTimeLeft + }); + } } + + return result; + })); + + // 等待当前批次完成 + await Promise.all(batchTasks); + + // 批次完成后,写入剩余缓冲区并释放内存 + if (writeBuffer.length > 0) { + batchWrite(writeBuffer); + writeBuffer = []; } - // 性能日志 - if (processedCount > 0 && processedCount % 1000 === 0) { + // 每1000个文件输出一次进度(减少日志) + if (processedCount % 1000 === 0) { const elapsed = (Date.now() - startTime) / 1000; const speed = processedCount / elapsed; - console.log(`⚡ Performance: ${speed.toFixed(1)} images/sec, ${processedCount}/${total} completed`); + const percent = ((processedCount / total) * 100).toFixed(1); + console.log(`⚡ ${processedCount}/${total} (${percent}%) | ${speed.toFixed(1)} 张/秒`); } - })); - - // 等待所有任务完成 - await Promise.all(tasks); + + // 每 1000 个文件触发一次 GC + if (processedCount > 0 && processedCount % 1000 === 0 && global.gc) { + global.gc(); + } + } // 写入剩余的缓冲区数据 if (writeBuffer.length > 0) { @@ -474,16 +483,8 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume writeBuffer = []; } - // 处理停止情况 - if (results.stopped) { - const pendingFiles = files.slice(processedCount); - scanManager.stopScan(libraryId, pendingFiles); - console.log(`⏸️ Scan stopped at ${processedCount}/${total}, ${pendingFiles.length} files pending`); - return results; - } - const totalTime = (Date.now() - startTime) / 1000; - console.log(`✅ Scan completed in ${totalTime.toFixed(1)}s, speed: ${(total / totalTime).toFixed(1)} images/sec`); + console.log(`✅ 扫描完成: ${total} 个文件 (${totalTime.toFixed(1)}秒, ${(total / totalTime).toFixed(1)} 张/秒)`); // Update folder image counts db.updateAllFolderCounts(); @@ -492,11 +493,9 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume if (libraryId) { scanManager.completeScan(libraryId); } - - console.log('Scan complete:', results); return results; } catch (error) { - console.error('Error scanning library:', error); + console.error('❌ 扫描失败:', error.message); if (libraryId) { scanManager.completeScan(libraryId); } @@ -517,25 +516,26 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr currentFiles.map(file => path.relative(libraryPath, file).replace(/\\/g, '/')) ); - // Get database files (已经是正斜杠格式) - const dbImages = db.getAllImages(); - const dbPaths = new Set(dbImages.map(img => (img.path || '').replace(/\\/g, '/'))); + // Get database files (只获取路径,不加载完整数据) + const dbPaths = new Set(); + const stmt = db.db.prepare('SELECT path FROM images'); + for (const row of stmt.iterate()) { + dbPaths.add((row.path || '').replace(/\\/g, '/')); + } // Find new, modified, and deleted files const toAdd = [...currentPaths].filter(p => !dbPaths.has(p)); const toCheck = [...currentPaths].filter(p => dbPaths.has(p)); let toDelete = [...dbPaths].filter(p => !currentPaths.has(p)); - console.log(`Sync: ${toAdd.length} new, ${toCheck.length} to check, ${toDelete.length} deleted`); + console.log(`🔄 同步: +${toAdd.length} 检查${toCheck.length} -${toDelete.length}`); // 安全检查:如果要删除的文件数量超过数据库中文件的50%,可能是路径匹配问题 - if (toDelete.length > 0 && dbImages.length > 0) { - const deleteRatio = toDelete.length / dbImages.length; + const dbImageCount = dbPaths.size; + if (toDelete.length > 0 && dbImageCount > 0) { + const deleteRatio = toDelete.length / dbImageCount; if (deleteRatio > 0.5 && toDelete.length > 10) { - console.warn(`⚠️ 安全检查:要删除 ${toDelete.length}/${dbImages.length} (${(deleteRatio * 100).toFixed(1)}%) 的文件,这可能是路径匹配问题,跳过删除操作`); - console.log('示例 currentPath:', [...currentPaths].slice(0, 3)); - console.log('示例 dbPath:', [...dbPaths].slice(0, 3)); - // 清空 toDelete,不执行删除 + console.warn(`⚠️ 安全检查: 跳过删除 ${toDelete.length}/${dbImageCount} 个文件 (${(deleteRatio * 100).toFixed(1)}%)`); toDelete = []; } } @@ -575,7 +575,9 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr return existing.file_hash !== currentHash; }).length; - console.log(`Found ${modifiedCount} modified files (skipped, hash unchanged)`); + if (modifiedCount > 0) { + console.log(`📝 发现 ${modifiedCount} 个修改文件`); + } // Delete removed files for (const relativePath of toDelete) { @@ -585,7 +587,7 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr // Rebuild folder structure if there are changes or forced if (toAdd.length > 0 || toDelete.length > 0 || forceRebuildFolders) { - console.log('Rebuilding folder structure...'); + console.log('📂 重建文件夹结构...'); // Get current folder structure from file system const currentFolders = await getFolderStructure(libraryPath); @@ -609,10 +611,11 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr db.deleteFolder(folder.path); }); - console.log(`Folders: +${foldersToAdd.length}, -${foldersToDelete.length}`); + if (foldersToAdd.length > 0 || foldersToDelete.length > 0) { + console.log(`📂 文件夹变化: +${foldersToAdd.length} -${foldersToDelete.length}`); + } // Update folder image counts - console.log('Updating folder image counts...'); const affectedFolders = new Set(); // Collect all affected folders (including parent folders) @@ -632,12 +635,10 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr affectedFolders.forEach(folderPath => { db.updateFolderImageCount(folderPath); }); - - console.log(`Updated ${affectedFolders.size} folder counts`); } const totalTime = (Date.now() - startTime) / 1000; - console.log(`✅ Sync completed in ${totalTime.toFixed(1)}s`); + console.log(`✅ 同步完成 (${totalTime.toFixed(1)}秒)`); return { added: toAdd.length, @@ -645,7 +646,7 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr deleted: toDelete.length }; } catch (error) { - console.error('Error syncing library:', error); + console.error('❌ 同步失败:', error.message); throw error; } } @@ -662,19 +663,23 @@ async function quickSync(libraryPath, db) { currentFiles.map(file => path.relative(libraryPath, file).replace(/\\/g, '/')) ); - // 获取数据库文件 - const dbImages = db.getAllImages(); - const dbPaths = new Set(dbImages.map(img => (img.path || '').replace(/\\/g, '/'))); + // 获取数据库文件(只获取路径,不加载完整数据) + const dbPaths = new Set(); + const stmt = db.db.prepare('SELECT path FROM images'); + for (const row of stmt.iterate()) { + dbPaths.add((row.path || '').replace(/\\/g, '/')); + } // 只检查新增和删除(不检查修改) const toAdd = [...currentPaths].filter(p => !dbPaths.has(p)); let toDelete = [...dbPaths].filter(p => !currentPaths.has(p)); // 安全检查 - if (toDelete.length > 0 && dbImages.length > 0) { - const deleteRatio = toDelete.length / dbImages.length; + const dbImageCount = dbPaths.size; + if (toDelete.length > 0 && dbImageCount > 0) { + const deleteRatio = toDelete.length / dbImageCount; if (deleteRatio > 0.5 && toDelete.length > 10) { - console.warn(`⚠️ 安全检查:跳过删除 ${toDelete.length} 个文件`); + console.warn(`⚠️ 跳过删除 ${toDelete.length} 个文件`); toDelete = []; } } @@ -690,7 +695,7 @@ async function quickSync(libraryPath, db) { } await processImage(fullPath, libraryPath, db); } catch (err) { - console.error(`Error adding ${relativePath}:`, err.message); + console.error(`❌ 添加失败 ${relativePath}:`, err.message); } } @@ -706,7 +711,7 @@ async function quickSync(libraryPath, db) { const elapsed = Date.now() - startTime; if (toAdd.length > 0 || toDelete.length > 0) { - console.log(`Quick sync: +${toAdd.length} -${toDelete.length} (${elapsed}ms)`); + console.log(`⚡ 快速同步: +${toAdd.length} -${toDelete.length} (${elapsed}ms)`); } return { added: toAdd.length, deleted: toDelete.length }; diff --git a/flypic/app/server/utils/thumbnail.js b/flypic/app/server/utils/thumbnail.js index f010f9d..45d4b98 100644 --- a/flypic/app/server/utils/thumbnail.js +++ b/flypic/app/server/utils/thumbnail.js @@ -3,6 +3,16 @@ const path = require('path'); const fs = require('fs'); const crypto = require('crypto'); +// 配置 Sharp 内存限制(防止内存泄漏) +sharp.cache({ + memory: 50, // 最大缓存 50MB(默认 50MB) + files: 0, // 禁用文件缓存 + items: 20 // 最多缓存 20 个操作 +}); + +// 设置并发限制 +sharp.concurrency(1); // 一次只处理 1 张图片 + // 支持的文件格式(确定可以生成缩略图的) const IMAGE_FORMATS = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'tiff', 'tif', 'avif', 'heif', 'heic', 'svg']; @@ -81,10 +91,15 @@ function isImageFile(filename) { * Calculate file hash for change detection */ function calculateFileHash(filePath) { - const fileBuffer = fs.readFileSync(filePath); + let fileBuffer = fs.readFileSync(filePath); const hashSum = crypto.createHash('md5'); hashSum.update(fileBuffer); - return hashSum.digest('hex'); + const hash = hashSum.digest('hex'); + + // 显式释放 Buffer + fileBuffer = null; + + return hash; } /** @@ -157,7 +172,7 @@ function getThumbnailConfig(originalWidth, originalHeight, targetHeight = 200) { async function generateThumbnail(inputPath, outputPath, targetHeight = 200) { try { // 先读取文件到 Buffer,避免 Sharp 锁定文件句柄 - const inputBuffer = fs.readFileSync(inputPath); + let inputBuffer = fs.readFileSync(inputPath); // Get image metadata from buffer const metadata = await sharp(inputBuffer).metadata(); @@ -219,17 +234,18 @@ async function generateThumbnail(inputPath, outputPath, targetHeight = 200) { }) .toFile(outputPath); + // 显式释放 Buffer 内存 + inputBuffer = null; + + // 强制 GC(如果可用) + if (global.gc && Math.random() < 0.1) { // 10% 概率执行 GC + global.gc(); + } + // 获取文件大小 const stats = fs.statSync(outputPath); const finalSize = stats.size; - // 可选:输出详细信息(每100张输出一次,避免日志过多) - const shouldLog = Math.random() < 0.01; // 1% 概率输出 - if (shouldLog) { - const sizeKB = (finalSize / 1024).toFixed(1); - console.log(`📸 Thumbnail: ${config.megaPixels}MP → ${config.width}x${config.height} (${sizeKB}KB, Q${quality}, ratio ${downscaleRatio.toFixed(1)}x)`); - } - return { width: config.width, height: config.height, @@ -291,7 +307,7 @@ async function getImageMetadata(imagePath) { /** * Generate thumbnail for a file (image/video/document) - * 使用 480px 高度 + * 使用 480px 高度(与 Billfish 一致) */ async function generateImageThumbnails(imagePath, libraryPath) { const flypicDir = path.join(libraryPath, '.flypic'); @@ -299,8 +315,6 @@ async function generateImageThumbnails(imagePath, libraryPath) { const hash = crypto.createHash('md5').update(relativePath).digest('hex'); const fileType = getFileType(imagePath); - console.log(`📝 Processing file: ${path.basename(imagePath)}, type: ${fileType}`); - // Sharding: use first 2 chars of hash for subdirectories (e.g. /ab/) const shard1 = hash.slice(0, 2); // 1-level sharding: .flypic/thumbnails/ab/hash.webp @@ -317,36 +331,32 @@ async function generateImageThumbnails(imagePath, libraryPath) { thumbnailResult = await generateThumbnail(imagePath, out480, 480); } else if (fileType === 'video') { // 视频:尝试提取封面 - console.log(`🎬 Extracting video thumbnail for: ${path.basename(imagePath)}`); thumbnailResult = await extractVideoThumbnail(imagePath, out480); // 如果提取失败,生成占位图 if (!thumbnailResult) { - console.log(`🎬 Generating video placeholder for: ${path.basename(imagePath)}`); thumbnailResult = await generatePlaceholderThumbnail(out480, 'video', ext); } } else if (fileType === 'design') { // 设计文件:尝试提取嵌入缩略图(仅 PSD) if (ext.toLowerCase() === 'psd') { - console.log(`🎨 Extracting PSD thumbnail for: ${path.basename(imagePath)}`); thumbnailResult = await extractPSDThumbnail(imagePath, out480); } // 如果提取失败或不是 PSD,生成占位图 if (!thumbnailResult) { - console.log(`🎨 Generating design placeholder for: ${path.basename(imagePath)}`); thumbnailResult = await generatePlaceholderThumbnail(out480, 'design', ext); } } else { // 其他类型(音频/文档/未知):生成占位图 - console.log(`📦 Generating ${fileType} placeholder for: ${path.basename(imagePath)}`); thumbnailResult = await generatePlaceholderThumbnail(out480, fileType, ext); } - console.log(`✅ Thumbnail generated: ${path.basename(out480)}, ${thumbnailResult.width}x${thumbnailResult.height}, ${(thumbnailResult.size / 1024).toFixed(1)}KB`); + // 返回相对于 libraryPath 的路径(包含 .flypic 前缀) + const thumbnailPath = path.relative(libraryPath, out480).replace(/\\/g, '/'); return { - thumbnail_path: path.relative(flypicDir, out480), + thumbnail_path: thumbnailPath, thumbnail_size: thumbnailResult.size, width: thumbnailResult.width, height: thumbnailResult.height, @@ -399,7 +409,6 @@ async function extractPSDThumbnail(psdPath, outputPath) { // 先获取原始缩略图尺寸 const metadata = await sharp(jpegData).metadata(); - console.log(` 📐 PSD embedded thumbnail: ${metadata.width}x${metadata.height}`); // 使用高质量缩放,保持宽高比 const aspectRatio = metadata.width / metadata.height; @@ -449,7 +458,6 @@ async function extractPSDThumbnail(psdPath, outputPath) { .toFile(outputPath); const stats = fs.statSync(outputPath); - console.log(` ✅ PSD thumbnail extracted: ${(stats.size / 1024).toFixed(1)}KB`); return { width: targetWidth, height: targetHeight, @@ -496,7 +504,6 @@ async function extractVideoThumbnail(videoPath, outputPath) { if (fs.existsSync(tempJpg)) { // 先获取实际尺寸 const metadata = await sharp(tempJpg).metadata(); - console.log(` 📐 Video frame: ${metadata.width}x${metadata.height}`); // 保持宽高比缩放到 480 高度 const aspectRatio = metadata.width / metadata.height; @@ -516,7 +523,6 @@ async function extractVideoThumbnail(videoPath, outputPath) { fs.unlinkSync(tempJpg); // 删除临时 JPG const stats = fs.statSync(outputPath); - console.log(` ✅ Video thumbnail extracted: ${targetWidth}x${targetHeight}, ${(stats.size / 1024).toFixed(1)}KB`); return { width: targetWidth, height: targetHeight, @@ -617,18 +623,6 @@ async function generatePlaceholderThumbnail(outputPath, type, label) { }; } -/** - * 获取文件类型对应的图标(Unicode) - */ -function getIconForType(type) { - const icons = { - video: '🎬', - document: '📄', - special: '🎨' - }; - return icons[type] || '📁'; -} - module.exports = { isImageFile, getFileType, diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 9baf694..1459c41 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -57,7 +57,6 @@ function App() { ? 'http://localhost:15002' // 开发模式:后端端口 : window.location.origin; // 生产模式:同源 - console.log('🔌 Connecting to Socket.IO:', socketUrl); const socket = io(socketUrl, { transports: ['websocket', 'polling'], // 优先使用 websocket reconnection: true, @@ -66,19 +65,34 @@ function App() { }); socket.on('connect', () => { - console.log('✅ Socket.IO connected:', socket.id); - }); - - socket.on('disconnect', () => { - console.log('❌ Socket.IO disconnected'); + // 连接后检查扫描状态 + const checkScanStatus = (retries = 5, delay = 1000) => { + const currentLibId = useLibraryStore.getState().currentLibraryId; + if (!currentLibId) return; + + scanAPI.getStatus(currentLibId).then(res => { + const scanStatus = res.data || res; + + if (scanStatus && scanStatus.status === 'scanning' && scanStatus.progress) { + setScanProgress(scanStatus.progress); + } else if (retries > 0) { + setTimeout(() => checkScanStatus(retries - 1, delay), delay); + } + }).catch((err) => { + if (retries > 0) { + setTimeout(() => checkScanStatus(retries - 1, delay), delay); + } + }); + }; + + checkScanStatus(5, 1000); }); socket.on('connect_error', (error) => { - console.error('❌ Socket.IO connection error:', error); + console.error('❌ 连接错误:', error.message); }); socket.on('scanProgress', (progress) => { - // 只显示当前素材库的进度 const currentLibId = useLibraryStore.getState().currentLibraryId; if (progress.libraryId === currentLibId) { setScanProgress(progress); @@ -86,14 +100,9 @@ function App() { }); socket.on('scanComplete', ({ libraryId, results }) => { - console.log('📊 Scan complete:', { libraryId, results }); - - // Only reload if this is the current library const currentLibId = useLibraryStore.getState().currentLibraryId; - console.log('🔍 Current library:', currentLibId, 'Scan library:', libraryId, 'Match:', libraryId === currentLibId); if (libraryId === currentLibId) { - console.log('🔄 Reloading folders and images...'); // 获取当前的筛选条件 const imageState = useImageStore.getState(); @@ -119,33 +128,22 @@ function App() { ]).then(([foldersRes, imagesRes, countRes]) => { useImageStore.getState().setFolders(foldersRes.folders); useImageStore.getState().setImages(imagesRes.images); - // 更新图片总数 useImageStore.getState().setTotalImageCount(countRes.count); - - console.log(`✅ Data reloaded, total: ${countRes.count}`); }).catch(err => { - console.error('❌ Error reloading data:', err); + console.error('❌ 加载数据失败:', err.message); }).finally(() => { - // 最后清除进度 setScanProgress(null); - console.log('✅ Scan progress cleared'); }); } else { - console.log('⚠️ Library mismatch, skipping reload'); - // 不是当前素材库,直接清除进度 setScanProgress(null); } }); socket.on('scanError', ({ libraryId, error }) => { setScanProgress(null); - console.error('Scan error:', error); + console.error('❌ 扫描错误:', error); }); - socket.on('scanPaused', ({ libraryId, results }) => { - console.log('⏸️ Scan paused:', { libraryId, results }); - // 保持进度显示,但标记为可以继续 - }); // Socket 监听已就绪后,再加载库并可能触发同步 loadLibraries(); @@ -160,18 +158,19 @@ function App() { const loadLibraries = async () => { try { const response = await libraryAPI.getAll(); - const { libraries, currentLibraryId: libId, theme: configTheme, preferences } = response; + const data = response.data || response; - // 立即更新基础状态 - setLibraries(libraries); - setCurrentLibrary(libId); + setLibraries(data.libraries || []); + setCurrentLibrary(data.currentLibraryId); + + const libId = data.currentLibraryId; // 加载主题和偏好设置 - if (configTheme) { - useUIStore.getState().setTheme(configTheme); + if (data.theme) { + useUIStore.getState().setTheme(data.theme); } - if (preferences) { - const { thumbnailHeight, leftPanelWidth, rightPanelWidth } = preferences; + if (data.preferences) { + const { thumbnailHeight, leftPanelWidth, rightPanelWidth } = data.preferences; if (thumbnailHeight) useUIStore.getState().setThumbnailHeight(thumbnailHeight); if (leftPanelWidth) setLeftWidth(leftPanelWidth); if (rightPanelWidth) setRightWidth(rightPanelWidth); @@ -191,27 +190,20 @@ function App() { const countRes = await imageAPI.getCount(libId); useImageStore.getState().setTotalImageCount(countRes.count); } catch (e) { - console.error('Failed to get image count:', e); + console.error('❌ 获取图片总数失败:', e.message); } - console.log('📂 数据加载完成,文件监控器将自动检测变化'); - - // 后台检查扫描状态(不阻塞主流程) + // 后台检查当前素材库的扫描状态 scanAPI.getStatus(libId).then(scanStatus => { - const { status, progress, pendingCount } = scanStatus; - if (status === 'scanning' || status === 'paused') { - console.log(`🔄 恢复扫描状态: ${status}, 进度: ${progress?.percent || 0}%`); - setScanProgress({ - ...progress, - canStop: true, - isPaused: status === 'paused', - pendingCount: pendingCount - }); + const { status, progress } = scanStatus; + if (status === 'scanning') { + setScanProgress(progress); } - }).catch(() => { }); // 忽略状态检查错误 + }).catch(() => { }); } + } catch (error) { - console.error('Error loading libraries:', error); + console.error('❌ 加载素材库失败:', error.message); } }; @@ -228,7 +220,7 @@ function App() { const response = await imageAPI.search(libraryId, params); useImageStore.getState().setImages(response.images); } catch (error) { - console.error('Error loading images:', error); + console.error('❌ 加载图片失败:', error.message); } }; @@ -237,7 +229,7 @@ function App() { const response = await imageAPI.getFolders(libraryId); useImageStore.getState().setFolders(response.folders); } catch (error) { - console.error('Error loading folders:', error); + console.error('❌ 加载文件夹失败:', error.message); } }; @@ -249,7 +241,7 @@ function App() { rightPanelWidth: right }); } catch (error) { - console.error('Error saving panel widths:', error); + console.error('❌ 保存面板宽度失败:', error.message); } }; diff --git a/frontend/src/api/endpoints/scan.js b/frontend/src/api/endpoints/scan.js index ac02ba9..acfa3a2 100644 --- a/frontend/src/api/endpoints/scan.js +++ b/frontend/src/api/endpoints/scan.js @@ -1,47 +1,21 @@ /** - * 扫描 API + * 扫描 API(简化版) */ import { api } from '../client'; -/** - * 全量扫描 - */ export async function fullScan(libraryId, wait = false) { return api.post('/scan/full', { libraryId, wait }); } -/** - * 增量同步 - */ export async function sync(libraryId, wait = false) { return api.post('/scan/sync', { libraryId, wait }); } -/** - * 停止扫描 - */ -export async function stop(libraryId) { - return api.post('/scan/stop', { libraryId }); -} - -/** - * 继续扫描 - */ -export async function resume(libraryId) { - return api.post('/scan/resume', { libraryId }); -} - -/** - * 获取扫描状态 - */ export async function getStatus(libraryId) { return api.get(`/scan/status/${libraryId}`); } -/** - * 修复文件夹路径 - */ export async function fixFolders(libraryId) { return api.post('/scan/fix-folders', { libraryId }); } diff --git a/frontend/src/components/MainContent.jsx b/frontend/src/components/MainContent.jsx index cd0df09..00f7de5 100644 --- a/frontend/src/components/MainContent.jsx +++ b/frontend/src/components/MainContent.jsx @@ -1,10 +1,9 @@ import { useEffect, useRef, useState, useCallback } from 'react'; -import { Pause, Play } from 'lucide-react'; import { useLibraryStore } from '../stores/useLibraryStore'; import { useImageStore } from '../stores/useImageStore'; import { useUIStore } from '../stores/useUIStore'; import { useScanStore } from '../stores/useScanStore'; -import { imageAPI, scanAPI } from '../api'; +import { imageAPI } from '../api'; import { onUserActionStart, onUserActionEnd } from '../services/imageLoadService'; import requestManager, { RequestType } from '../services/requestManager'; import imageCache from '../utils/imageCache'; @@ -21,9 +20,6 @@ function MainContent() { const currentRequestContextRef = useRef(null); // 文件夹切换防抖 const debounceTimerRef = useRef(null); - // 扫描控制 - const [scanPaused, setScanPaused] = useState(false); - const [isStoppingOrResuming, setIsStoppingOrResuming] = useState(false); // 计算预估剩余时间 const getEstimatedTime = () => { @@ -116,8 +112,6 @@ function MainContent() { hasMore: hasMore || false, }); - console.log(`[MainContent] Loaded page: +${images.length}, total: ${(isInitialLoad ? images.length : imageLoadingState.loadedCount + images.length)}/${total}`); - // 如果还有更多数据,恢复空闲加载 if (hasMore) { onUserActionEnd(hasMore); @@ -187,83 +181,26 @@ function MainContent() { }; }, [cancelCurrentRequest]); - // 停止扫描 - const handleStopScan = async () => { - if (!currentLibraryId || isStoppingOrResuming) return; - setIsStoppingOrResuming(true); - try { - await scanAPI.stop(currentLibraryId); - setScanPaused(true); - } catch (error) { - console.error('Error stopping scan:', error); - } finally { - setIsStoppingOrResuming(false); - } - }; - - // 继续扫描 - const handleResumeScan = async () => { - if (!currentLibraryId || isStoppingOrResuming) return; - setIsStoppingOrResuming(true); - try { - if (scanProgress?.needsRescan) { - await scanAPI.sync(currentLibraryId); - } else { - await scanAPI.resume(currentLibraryId); - } - setScanPaused(false); - } catch (error) { - console.error('Error resuming scan:', error); - } finally { - setIsStoppingOrResuming(false); - } - }; - - // 同步扫描暂停状态 - useEffect(() => { - if (!scanProgress) { - setScanPaused(false); - } else if (scanProgress.isPaused) { - setScanPaused(true); - } else if (scanProgress.percent === 100) { - setScanPaused(false); - } - }, [scanProgress]); - return (
- {/* Scan Progress */} + {/* Scan Progress - 简化版,无暂停按钮 */} {scanProgress && ( -
+
-
- {scanPaused ? '扫描已暂停' : scanProgress?.status === 'preparing' ? '正在准备扫描...' : '正在扫描素材库,期间建议勿操作,否则会影响扫描速度'} -
-
- - {scanProgress?.percent || 0}% - - {(scanProgress?.canStop || scanPaused) && ( - - )} +
+ {scanProgress?.status === 'preparing' ? '正在准备扫描...' : '正在扫描素材库...'}
+ + {scanProgress?.percent || 0}% +
-
+
-
+
已处理 {scanProgress?.current || 0} / {scanProgress?.total || 0} 张图片 {getEstimatedTime() && ` · ${getEstimatedTime()}`}
diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsx index 728ae91..7ed2ab9 100644 --- a/frontend/src/components/Sidebar.jsx +++ b/frontend/src/components/Sidebar.jsx @@ -7,11 +7,11 @@ import { libraryAPI, scanAPI, imageAPI } from '../api'; import requestManager from '../services/requestManager'; import { onUserActionStart } from '../services/imageLoadService'; -// 检查素材库是否有暂停的扫描 -const checkPausedScan = async (libraryId) => { +// 检查素材库扫描状态 +const checkScanStatus = async (libraryId) => { try { const response = await scanAPI.getStatus(libraryId); - return response.data; + return response.data || response; } catch (error) { return null; } @@ -20,6 +20,7 @@ const checkPausedScan = async (libraryId) => { function Sidebar() { const { libraries, currentLibraryId, setCurrentLibrary, addLibrary, removeLibrary } = useLibraryStore(); const { folders, selectedFolder, totalImageCount, setSelectedFolder } = useImageStore(); + const { isScanning } = useScanStore(); const [showAddLibrary, setShowAddLibrary] = useState(false); const [newLibraryName, setNewLibraryName] = useState(''); @@ -54,6 +55,12 @@ function Sidebar() { }, []); const handleAddLibrary = async () => { + // 扫描期间禁止添加素材库 + if (isScanning()) { + alert('扫描进行中,请稍后再试或暂停扫描'); + return; + } + if (!newLibraryName.trim()) { alert('请输入素材库名称'); return; @@ -137,7 +144,29 @@ function Sidebar() { console.log('✅ 扫描已启动,请等待进度显示...'); } catch (error) { console.error('❌ Error adding library:', error); - alert('添加素材库失败: ' + error.message); + + // 提取错误信息 + let errorMessage = error.message || '未知错误'; + + // 如果是后端返回的错误响应 + if (error.response?.data?.message) { + errorMessage = error.response.data.message; + } + + // 特殊处理权限错误 + if (errorMessage.includes('无法访问') || errorMessage.includes('权限') || errorMessage.includes('数据共享')) { + alert( + '⚠️ 文件夹权限不足\n\n' + + errorMessage + '\n\n' + + '操作步骤:\n' + + '1. 应用中心找到 FlyPic 应用\n' + + '2. 点击 应用设置\n' + + '3. 将该文件夹添加到 FlyPic 应用的读写权限' + ); + } else { + alert('添加素材库失败: ' + errorMessage); + } + useScanStore.getState().setScanProgress(null); setIsAdding(false); } @@ -145,6 +174,12 @@ function Sidebar() { const handleLibraryClick = async (libraryId) => { if (libraryId === currentLibraryId) return; + + // 扫描期间禁止切换素材库 + if (isScanning()) { + alert('扫描进行中,请稍后再试或暂停扫描'); + return; + } setIsSwitching(true); try { @@ -178,31 +213,12 @@ function Sidebar() { useImageStore.getState().setTotalImageCount(countRes.count); setCurrentLibrary(libraryId); // 最后才更新 currentLibraryId - // 7. 后台检查新素材库是否有暂停的扫描(不阻塞主流程) - checkPausedScan(libraryId).then(scanStatus => { - if (scanStatus && scanStatus.status === 'paused') { - if (scanStatus.needsRescan) { - useScanStore.getState().setScanProgress({ - ...scanStatus.progress, - libraryId, - canStop: true, - isPaused: true, - pendingCount: scanStatus.progress?.total - scanStatus.progress?.current || 0, - needsRescan: true - }); - console.log(`⏸️ 发现中断的扫描,需要继续完成`); - } else if (scanStatus.pendingCount > 0) { - useScanStore.getState().setScanProgress({ - ...scanStatus.progress, - libraryId, - canStop: true, - isPaused: true, - pendingCount: scanStatus.pendingCount - }); - console.log(`⏸️ 发现暂停的扫描,待处理: ${scanStatus.pendingCount} 张`); - } + // 7. 检查新素材库是否正在扫描 + checkScanStatus(libraryId).then(scanStatus => { + if (scanStatus && scanStatus.status === 'scanning') { + useScanStore.getState().setScanProgress(scanStatus.progress); } - }).catch(() => { }); // 忽略状态检查错误 + }).catch(() => { }); } catch (error) { console.error('Error setting current library:', error); alert('切换素材库失败: ' + error.message); @@ -215,6 +231,12 @@ function Sidebar() { const handleDeleteLibrary = async () => { if (!currentLibraryId) return; + + // 扫描期间禁止删除素材库 + if (isScanning()) { + alert('扫描进行中,请稍后再试或暂停扫描'); + return; + } const currentLib = libraries.find(lib => lib.id === currentLibraryId); if (!currentLib) return; @@ -453,12 +475,16 @@ function Sidebar() { onChange={(e) => { const value = e.target.value; if (value === '__add__') { + if (isScanning()) { + alert('扫描进行中,请稍后再试或暂停扫描'); + return; + } setShowAddLibrary(true); } else if (value) { handleLibraryClick(value); } }} - disabled={isSwitching} + disabled={isSwitching || isScanning()} className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 appearance-none cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed" style={{ paddingRight: '2rem' }} > @@ -480,8 +506,9 @@ function Sidebar() { {currentLibraryId && libraries.length > 0 && ( diff --git a/frontend/src/stores/useScanStore.js b/frontend/src/stores/useScanStore.js index 519b802..691fdc7 100644 --- a/frontend/src/stores/useScanStore.js +++ b/frontend/src/stores/useScanStore.js @@ -1,45 +1,38 @@ /** - * 扫描状态管理 + * 扫描状态管理(简化版) */ import { create } from 'zustand'; export const useScanStore = create((set, get) => ({ - // 扫描进度 scanProgress: null, scanStartTime: null, - // 设置扫描进度 setScanProgress: (progress) => set((state) => { - // 第一次收到进度时记录开始时间 if (progress && !state.scanStartTime && progress.current > 0) { return { scanProgress: progress, scanStartTime: Date.now() }; } - - // 扫描结束时清空开始时间 if (!progress) { return { scanProgress: null, scanStartTime: null }; } - return { scanProgress: progress }; }), - // 清除扫描进度 clearScanProgress: () => set({ scanProgress: null, scanStartTime: null }), - // 获取预估剩余时间 getEstimatedTimeLeft: () => { const { scanProgress, scanStartTime } = get(); - if (!scanProgress || !scanStartTime || scanProgress.current === 0) { return null; } - const elapsed = Date.now() - scanStartTime; - const rate = scanProgress.current / elapsed; // 图片/毫秒 + const rate = scanProgress.current / elapsed; const remaining = scanProgress.total - scanProgress.current; - const estimatedMs = remaining / rate; - - return Math.ceil(estimatedMs / 1000); // 返回秒数 + return Math.ceil((remaining / rate) / 1000); + }, + + isScanning: () => { + const { scanProgress } = get(); + return scanProgress && scanProgress.status !== 'preparing'; } })); diff --git a/frontend/src/utils/imageCache.js b/frontend/src/utils/imageCache.js index 13c8ff1..ec7920d 100644 --- a/frontend/src/utils/imageCache.js +++ b/frontend/src/utils/imageCache.js @@ -109,8 +109,6 @@ class ImageCache { this.cache.clear(); this.accessOrder = []; - - console.log('[ImageCache] Cache cleared'); } /** @@ -124,7 +122,6 @@ class ImageCache { // First item in access order is least recently used const lruImageId = this.accessOrder[0]; - console.log(`[ImageCache] Evicting LRU: ${lruImageId}`); this.remove(lruImageId); this.stats.evictionCount++; } @@ -195,7 +192,7 @@ class ImageCache { */ logStats() { const stats = this.getStats(); - console.log('[ImageCache] Statistics:', stats); + // 仅在需要时输出统计信息 } } diff --git a/scripts/build-fpk-docker.js b/scripts/build-fpk-docker.js deleted file mode 100644 index 96659d3..0000000 --- a/scripts/build-fpk-docker.js +++ /dev/null @@ -1,172 +0,0 @@ -const { execSync } = require('child_process'); -const fs = require('fs'); -const path = require('path'); - -const root = path.join(__dirname, '..'); -const backendDir = path.join(root, 'backend'); -const frontendDir = path.join(root, 'frontend'); -const packDir = path.join(root, 'flypic'); -const packServerDir = path.join(packDir, 'app', 'server'); - -function run(cmd, options = {}) { - console.log(`> ${cmd}`); - execSync(cmd, { stdio: 'inherit', cwd: root, ...options }); -} - -console.log('=== 使用 Docker 构建 FlyPic 飞牛应用包 ===\n'); - -// 1. 构建前端 -console.log('1. 构建前端...'); -run(`cd ${frontendDir} && npm run build`); - -// 2. 清理并创建服务器目录 -console.log('\n2. 准备服务器目录...'); -if (fs.existsSync(packServerDir)) { - fs.rmSync(packServerDir, { recursive: true }); -} -fs.mkdirSync(packServerDir, { recursive: true }); - -// 3. 复制后端文件 -console.log('\n3. 复制后端文件...'); -const backendFiles = ['server.js', 'package.json', 'package-lock.json']; -backendFiles.forEach(file => { - const src = path.join(backendDir, file); - const dest = path.join(packServerDir, file); - if (fs.existsSync(src)) { - fs.copyFileSync(src, dest); - console.log(` 复制: ${file}`); - } -}); - -const backendDirs = ['routes', 'database', 'utils']; -backendDirs.forEach(dir => { - const src = path.join(backendDir, dir); - const dest = path.join(packServerDir, dir); - if (fs.existsSync(src)) { - fs.cpSync(src, dest, { recursive: true }); - console.log(` 复制目录: ${dir}/`); - } -}); - -// 4. 复制前端构建产物 -console.log('\n4. 复制前端构建产物...'); -const frontendDist = path.join(frontendDir, 'dist'); -const serverPublic = path.join(packServerDir, 'public'); -if (fs.existsSync(frontendDist)) { - fs.cpSync(frontendDist, serverPublic, { recursive: true }); - console.log(' 复制: frontend/dist -> app/server/public'); -} - -// 5. 使用 Docker 安装 Linux 版本的依赖(完整编译) -console.log('\n5. 使用 Docker 安装 Linux 依赖(完整编译原生模块)...'); -console.log(' 这将确保上传到飞牛后可以直接使用,无需额外操作\n'); - -// 转换 Windows 路径为 WSL 路径(Docker Desktop for Windows 需要) -const convertToWSLPath = (winPath) => { - // C:\Users\... -> /c/Users/... - return winPath.replace(/\\/g, '/').replace(/^([A-Z]):/, (match, drive) => `/${drive.toLowerCase()}`); -}; - -const wslPackServerDir = convertToWSLPath(packServerDir); - -// 完整安装方案:安装构建工具 + 完整编译所有原生模块 -const dockerCmd = `docker run --rm -v "${wslPackServerDir}:/app" -w /app node:22-slim bash -c "apt-get update -qq && apt-get install -y -qq build-essential python3 && npm config set registry https://registry.npmmirror.com && npm install --production && du -sh node_modules/"`; - -console.log(' 开始构建...'); -console.log(` Docker 挂载路径: ${wslPackServerDir}`); -console.log(' 提示:首次构建需要下载并编译,可能需要 5-10 分钟\n'); - -try { - run(dockerCmd); - - console.log('\n ✅ Linux 依赖完整编译成功!'); - console.log(' ✅ node_modules 已安装(约 57 MB)'); - console.log(' ✅ 包含 Sharp 和 better-sqlite3 的 Linux 版本'); - console.log(' ✅ 上传到飞牛后可直接使用,无需额外操作'); - console.log('\n 注意:如果看到权限错误,可以忽略,这是 Windows + Docker 的正常现象'); -} catch (error) { - console.error('\n ❌ Docker 编译失败'); - console.error(' 错误信息:', error.message); - console.log('\n 可能的原因:'); - console.log(' 1. Docker 未运行或未正确安装'); - console.log(' 2. 网络连接问题(无法下载依赖)'); - console.log(' 3. 磁盘空间不足'); - console.log('\n 解决方案:'); - console.log(' 1. 确保 Docker Desktop 正在运行'); - console.log(' 2. 在 Docker Desktop 设置中启用文件共享'); - console.log(' 3. 检查网络连接'); - console.log(' 4. 或使用方法二:在飞牛 fnOS 上手动安装依赖'); - process.exit(1); -} - -// 6. 创建UI配置 -console.log('\n6. 创建UI配置...'); -const uiConfigDir = path.join(packDir, 'app', 'ui'); -if (!fs.existsSync(uiConfigDir)) { - fs.mkdirSync(uiConfigDir, { recursive: true }); -} - -const uiConfig = { - ".url": { - "flypic.Application": { - "title": "FlyPic", - "icon": "images/icon-{0}.png", - "type": "url", - "protocol": "http", - "port": "15002", - "allUsers": true, - "control": { - "portPerm": "editable" - } - } - } -}; - -fs.writeFileSync( - path.join(uiConfigDir, 'config'), - JSON.stringify(uiConfig, null, 2) -); -console.log(' 创建: app/ui/config'); - -// 7. 创建其他必要的脚本 -console.log('\n7. 创建生命周期脚本...'); -const scripts = [ - 'uninstall_init', 'uninstall_callback', - 'upgrade_init', 'upgrade_callback', - 'config_init', 'config_callback' -]; - -scripts.forEach(script => { - const scriptPath = path.join(packDir, 'cmd', script); - if (!fs.existsSync(scriptPath)) { - fs.writeFileSync(scriptPath, '#!/bin/bash\nexit 0\n'); - console.log(` 创建: cmd/${script}`); - } -}); - -// 8. 确保所有脚本使用 LF 换行符 -console.log('\n8. 修复脚本换行符...'); -const cmdDir = path.join(packDir, 'cmd'); -if (fs.existsSync(cmdDir)) { - const allScripts = fs.readdirSync(cmdDir); - allScripts.forEach(script => { - const scriptPath = path.join(cmdDir, script); - if (fs.statSync(scriptPath).isFile()) { - let content = fs.readFileSync(scriptPath, 'utf8'); - content = content.replace(/\r\n/g, '\n'); - fs.writeFileSync(scriptPath, content, { encoding: 'utf8' }); - console.log(` 修复: cmd/${script}`); - } - }); -} - -console.log('\n=== 构建完成 ==='); -console.log(`\n打包目录: ${packDir}`); -console.log('\n✅ 已包含完整编译的 Linux 版本 node_modules'); -console.log('✅ 包含 Sharp (图片处理) 和 better-sqlite3 (数据库) 的原生模块'); -console.log('✅ 上传到飞牛后可直接使用,无需任何额外操作'); -console.log('\n下一步:'); -console.log('1. 上传 flypic 文件夹到飞牛 fnOS'); -console.log('2. 在飞牛 fnOS 上使用 fnpack build 打包'); -console.log(' cd flypic && fnpack build'); -console.log('3. 安装生成的 .fpk 文件即可使用'); diff --git a/scripts/build-fpk.js b/scripts/build-fpk.js deleted file mode 100644 index 31f195f..0000000 --- a/scripts/build-fpk.js +++ /dev/null @@ -1,136 +0,0 @@ -const { execSync } = require('child_process'); -const fs = require('fs'); -const path = require('path'); - -const root = path.join(__dirname, '..'); -const backendDir = path.join(root, 'backend'); -const frontendDir = path.join(root, 'frontend'); -const packDir = path.join(root, 'flypic'); -const packServerDir = path.join(packDir, 'app', 'server'); - -function run(cmd) { - console.log(`> ${cmd}`); - execSync(cmd, { stdio: 'inherit', cwd: root }); -} - -console.log('=== 构建 FlyPic 飞牛应用包 ===\n'); - -// 1. 构建前端 -console.log('1. 构建前端...'); -run(`cd ${frontendDir} && npm run build`); - -// 2. 清理并创建服务器目录 -console.log('\n2. 准备服务器目录...'); -if (fs.existsSync(packServerDir)) { - fs.rmSync(packServerDir, { recursive: true }); -} -fs.mkdirSync(packServerDir, { recursive: true }); - -// 3. 复制后端文件 -console.log('\n3. 复制后端文件...'); -const backendFiles = ['server.js', 'package.json', 'package-lock.json']; -backendFiles.forEach(file => { - const src = path.join(backendDir, file); - const dest = path.join(packServerDir, file); - if (fs.existsSync(src)) { - fs.copyFileSync(src, dest); - console.log(` 复制: ${file}`); - } -}); - -// 复制后端目录 -const backendDirs = ['routes', 'database', 'utils']; -backendDirs.forEach(dir => { - const src = path.join(backendDir, dir); - const dest = path.join(packServerDir, dir); - if (fs.existsSync(src)) { - fs.cpSync(src, dest, { recursive: true }); - console.log(` 复制目录: ${dir}/`); - } -}); - -// 4. 复制前端构建产物 -console.log('\n4. 复制前端构建产物...'); -const frontendDist = path.join(frontendDir, 'dist'); -const serverPublic = path.join(packServerDir, 'public'); -if (fs.existsSync(frontendDist)) { - fs.cpSync(frontendDist, serverPublic, { recursive: true }); - console.log(' 复制: frontend/dist -> app/server/public'); -} - -// 5. 跳过依赖安装(在目标系统上安装) -console.log('\n5. 跳过依赖安装(将在飞牛 fnOS 上安装)...'); - -// 6. 创建UI配置 -console.log('\n6. 创建UI配置...'); -const uiConfigDir = path.join(packDir, 'app', 'ui'); -if (!fs.existsSync(uiConfigDir)) { - fs.mkdirSync(uiConfigDir, { recursive: true }); -} - -const uiConfig = { - ".url": { - "flypic.Application": { - "title": "FlyPic", - "icon": "images/icon-{0}.png", - "type": "url", - "protocol": "http", - "port": "15002", - "allUsers": true, - "control": { - "portPerm": "editable" - } - } - } -}; - -fs.writeFileSync( - path.join(uiConfigDir, 'config'), - JSON.stringify(uiConfig, null, 2) -); -console.log(' 创建: app/ui/config'); - -// 7. 创建其他必要的脚本 -console.log('\n7. 创建生命周期脚本...'); -const scripts = [ - 'uninstall_init', 'uninstall_callback', - 'upgrade_init', 'upgrade_callback', - 'config_init', 'config_callback' -]; - -scripts.forEach(script => { - const scriptPath = path.join(packDir, 'cmd', script); - if (!fs.existsSync(scriptPath)) { - fs.writeFileSync(scriptPath, '#!/bin/bash\nexit 0\n'); - console.log(` 创建: cmd/${script}`); - } -}); - -// 8. 确保所有脚本使用 LF 换行符 -console.log('\n8. 修复脚本换行符...'); -const cmdDir = path.join(packDir, 'cmd'); -if (fs.existsSync(cmdDir)) { - const allScripts = fs.readdirSync(cmdDir); - allScripts.forEach(script => { - const scriptPath = path.join(cmdDir, script); - if (fs.statSync(scriptPath).isFile()) { - let content = fs.readFileSync(scriptPath, 'utf8'); - // 将 CRLF 转换为 LF - content = content.replace(/\r\n/g, '\n'); - fs.writeFileSync(scriptPath, content, { encoding: 'utf8' }); - console.log(` 修复: cmd/${script}`); - } - }); -} - -console.log('\n=== 构建完成 ==='); -console.log(`\n打包目录: ${packDir}`); -console.log('\n下一步:'); -console.log('1. 准备图标文件 (64x64 和 256x256)'); -console.log(' - flypic/app/ui/images/icon_64.png'); -console.log(' - flypic/app/ui/images/icon_256.png'); -console.log(' - flypic/ICON.PNG (256x256)'); -console.log(' - flypic/ICON_256.PNG (256x256)'); -console.log('2. 添加 LICENSE 文件'); -console.log('3. 在飞牛 fnOS 上使用 fnpack build 打包'); -console.log(' cd flypic && fnpack build'); diff --git a/scripts/build.js b/scripts/build.js new file mode 100644 index 0000000..47bca31 --- /dev/null +++ b/scripts/build.js @@ -0,0 +1,188 @@ +/** + * FlyPic 飞牛应用构建脚本 + * + * 使用 Docker (node:22-slim, Debian) 构建 Linux glibc 版本依赖 + * 确保与飞牛 fnOS (Debian 系) 兼容 + * + * 用法: node scripts/build.js + */ + +const { execSync } = require('child_process'); +const fs = require('fs'); +const path = require('path'); + +// 路径配置 +const root = path.join(__dirname, '..'); +const backendDir = path.join(root, 'backend'); +const frontendDir = path.join(root, 'frontend'); +const packDir = path.join(root, 'flypic'); +const packServerDir = path.join(packDir, 'app', 'server'); + +// 执行命令 +function run(cmd, options = {}) { + console.log(`> ${cmd}`); + execSync(cmd, { stdio: 'inherit', shell: true, ...options }); +} + +// 转换 Windows 路径为 Docker 挂载路径 +function toDockerPath(winPath) { + // C:\Users\... -> /c/Users/... + return winPath.replace(/\\/g, '/').replace(/^([A-Z]):/, (_, drive) => `/${drive.toLowerCase()}`); +} + +console.log('╔════════════════════════════════════════════════════════════╗'); +console.log('║ FlyPic 飞牛应用构建脚本 (Docker + Debian) ║'); +console.log('╚════════════════════════════════════════════════════════════╝\n'); + +// ============================================================ +// 1. 构建前端 +// ============================================================ +console.log('📦 [1/6] 构建前端...'); +run('npm run build', { cwd: frontendDir }); +console.log(' ✅ 前端构建完成\n'); + +// ============================================================ +// 2. 清理并准备服务器目录 +// ============================================================ +console.log('🧹 [2/6] 准备服务器目录...'); +if (fs.existsSync(packServerDir)) { + fs.rmSync(packServerDir, { recursive: true }); +} +fs.mkdirSync(packServerDir, { recursive: true }); +console.log(' ✅ 目录已清理\n'); + +// ============================================================ +// 3. 复制后端文件 +// ============================================================ +console.log('📋 [3/6] 复制后端文件...'); + +// 复制单文件 +const backendFiles = ['server.js', 'package.json']; +backendFiles.forEach(file => { + const src = path.join(backendDir, file); + const dest = path.join(packServerDir, file); + if (fs.existsSync(src)) { + fs.copyFileSync(src, dest); + console.log(` 复制: ${file}`); + } +}); + +// 复制目录 +const backendDirs = ['src', 'database', 'utils']; +backendDirs.forEach(dir => { + const src = path.join(backendDir, dir); + const dest = path.join(packServerDir, dir); + if (fs.existsSync(src)) { + fs.cpSync(src, dest, { recursive: true }); + console.log(` 复制目录: ${dir}/`); + } +}); +console.log(' ✅ 后端文件复制完成\n'); + +// ============================================================ +// 4. 复制前端构建产物 +// ============================================================ +console.log('🎨 [4/6] 复制前端构建产物...'); +const frontendDist = path.join(frontendDir, 'dist'); +const serverPublic = path.join(packServerDir, 'public'); +if (fs.existsSync(frontendDist)) { + fs.cpSync(frontendDist, serverPublic, { recursive: true }); + console.log(' 复制: frontend/dist -> app/server/public'); +} +console.log(' ✅ 前端产物复制完成\n'); + +// ============================================================ +// 5. 使用 Docker 安装 Linux 依赖 +// ============================================================ +console.log('🐳 [5/6] 使用 Docker 安装 Linux 依赖...'); +console.log(' 镜像: node:22-slim (Debian, glibc)'); +console.log(' 目标: 飞牛 fnOS (Debian 系)'); +console.log(' ⏳ 首次构建需要编译原生模块,约需 1-3 分钟...\n'); + +const dockerPath = toDockerPath(packServerDir); + +// 使用 node:22-slim (Debian) 确保 glibc 兼容性 +const dockerCmd = [ + 'docker run --rm', + `-v "${dockerPath}:/app"`, + '-w /app', + 'node:22-slim', + 'sh -c "' + [ + // 安装编译工具 + 'apt-get update', + 'apt-get install -y python3 make g++ --no-install-recommends', + // 配置 npm 镜像 + 'npm config set registry https://registry.npmmirror.com', + // 清理旧依赖并安装 + 'rm -rf node_modules package-lock.json', + 'npm install --production', + // 显示结果 + 'echo ""', + 'echo "=== 依赖安装完成 ==="', + 'du -sh node_modules/' + ].join(' && ') + '"' +].join(' '); + +try { + run(dockerCmd, { cwd: root }); + console.log('\n ✅ Linux 依赖安装成功'); + console.log(' ✅ 包含 sharp-linux-x64 (glibc 版本)'); + console.log(' ✅ 包含 better-sqlite3 (Linux 编译版本)\n'); +} catch (error) { + console.error('\n ❌ Docker 构建失败'); + console.error(' 错误:', error.message); + console.log('\n 请检查:'); + console.log(' 1. Docker Desktop 是否正在运行'); + console.log(' 2. 是否有 node:22-slim 镜像 (docker pull node:22-slim)'); + console.log(' 3. 网络连接是否正常'); + process.exit(1); +} + +// ============================================================ +// 6. 修复脚本换行符 (Windows -> Unix) +// ============================================================ +console.log('🔧 [6/6] 修复脚本换行符...'); +const cmdDir = path.join(packDir, 'cmd'); +if (fs.existsSync(cmdDir)) { + const scripts = fs.readdirSync(cmdDir); + scripts.forEach(script => { + const scriptPath = path.join(cmdDir, script); + if (fs.statSync(scriptPath).isFile()) { + let content = fs.readFileSync(scriptPath, 'utf8'); + content = content.replace(/\r\n/g, '\n'); + fs.writeFileSync(scriptPath, content, { encoding: 'utf8' }); + console.log(` 修复: cmd/${script}`); + } + }); +} +console.log(' ✅ 换行符修复完成\n'); + +// ============================================================ +// 完成 +// ============================================================ +console.log('╔════════════════════════════════════════════════════════════╗'); +console.log('║ 🎉 构建完成! ║'); +console.log('╚════════════════════════════════════════════════════════════╝\n'); + +console.log(`📁 打包目录: ${packDir}\n`); + +console.log('📦 包含内容:'); +console.log(' • app/server/ 后端代码 + 前端构建产物'); +console.log(' • app/server/node_modules/ Linux glibc 依赖 (~57MB)'); +console.log(' • app/ui/ UI 配置'); +console.log(' • cmd/ 生命周期脚本'); +console.log(' • config/ 资源配置'); +console.log(' • wizard/ 安装向导'); +console.log(' • manifest 应用清单'); +console.log(' • ICON*.PNG 应用图标\n'); + +console.log('📋 下一步:'); +console.log(' 1. 上传 flypic 文件夹到飞牛 NAS'); +console.log(' 例如: /vol1/1000/flypic'); +console.log(''); +console.log(' 2. SSH 登录飞牛,打包应用:'); +console.log(' cd /vol1/1000/flypic'); +console.log(' fnpack build'); +console.log(''); +console.log(' 3. 安装生成的 .fpk 文件'); +console.log(' 在应用中心 -> 手动安装 -> 选择 flypic_x.x.x_all.fpk'); diff --git a/scripts/test-in-docker.js b/scripts/test-in-docker.js deleted file mode 100644 index 41977c3..0000000 --- a/scripts/test-in-docker.js +++ /dev/null @@ -1,55 +0,0 @@ -const { execSync } = require('child_process'); -const path = require('path'); -const fs = require('fs'); -const os = require('os'); - -const packServerDir = path.resolve(__dirname, '../flypic/app/server'); - -console.log('=== 在 Docker 中测试 FlyPic ===\n'); - -// 创建临时启动脚本 -const startScript = `#!/bin/bash -set -e -export PORT=5002 -export FRONTEND_DIST=/app/public -mkdir -p /tmp/flypic_data -echo "Environment variables set" -echo "PORT=$PORT" -echo "FRONTEND_DIST=$FRONTEND_DIST" -echo "Current directory: $(pwd)" -echo "Files in /app:" -ls -la /app -echo "" -echo "Files in /app/public:" -ls -la /app/public || echo "public directory not found" -echo "" -echo "Starting server..." -node server.js -`; - -// 写入临时脚本文件 -const tmpScript = path.join(os.tmpdir(), 'flypic-start.sh'); -fs.writeFileSync(tmpScript, startScript); - -const dockerCmd = `docker run --rm -it -v "${packServerDir}:/app" -v "${tmpScript}:/start.sh" -w /app -p 5002:5002 node:22-slim bash /start.sh`; - -console.log('提示:'); -console.log('- 服务将在 http://localhost:5002 运行'); -console.log('- 按 Ctrl+C 停止服务'); -console.log('- 这是测试 Linux 版本依赖是否正常'); -console.log('\n正在启动...\n'); - -try { - execSync(dockerCmd, { stdio: 'inherit' }); -} catch (error) { - if (error.signal === 'SIGINT') { - console.log('\n服务已停止'); - } else { - console.log('\n启动失败,错误信息见上方'); - } -} finally { - // 清理临时文件 - if (fs.existsSync(tmpScript)) { - fs.unlinkSync(tmpScript); - } -} diff --git a/飞牛打包部署指南.md b/飞牛打包部署指南.md index caa5e41..d330b01 100644 --- a/飞牛打包部署指南.md +++ b/飞牛打包部署指南.md @@ -9,35 +9,28 @@ - Docker Desktop(用于编译 Linux 版本依赖) ### 飞牛 NAS -- fnOS 系统 -- fnpack 命令行工具(通过 `npm install -g fnpack` 安装) +- fnOS 0.9.27+ +- fnpack 命令行工具(系统预装或通过 `npm install -g fnpack` 安装) ## 一、构建应用 -### 方法一:使用 Docker 构建(推荐) +### 使用 Docker 构建(推荐) -此方法会自动编译 Linux 版本的原生模块(Sharp、better-sqlite3),上传到飞牛后可直接使用。 +此方法使用 `node:22-slim` (Debian) 镜像编译原生模块,确保与飞牛 fnOS (Debian 系) 的 glibc 兼容。 ```bash # 确保 Docker Desktop 正在运行 -node scripts/build-fpk-docker.js +node scripts/build.js ``` -构建完成后,`flypic` 目录将包含: -- `app/server/` - 后端代码和前端构建产物 -- `app/server/node_modules/` - Linux 版本的依赖(约 50MB) -- `app/ui/` - 应用 UI 配置 -- `cmd/` - 生命周期脚本 -- `wizard/` - 安装向导配置 -- `manifest` - 应用清单 +构建过程: +1. 构建前端 (Vite) +2. 复制后端代码到 `flypic/app/server/` +3. 复制前端产物到 `flypic/app/server/public/` +4. 使用 Docker 安装 Linux glibc 版本依赖 +5. 修复脚本换行符 (CRLF → LF) -### 方法二:仅构建代码(需在飞牛上安装依赖) - -```bash -node scripts/build-fpk.js -``` - -此方法不包含 node_modules,需要在飞牛 NAS 上手动安装依赖。 +构建完成后,`flypic` 目录即可上传到飞牛。 ## 二、上传到飞牛 NAS @@ -60,7 +53,7 @@ cd /vol1/1000/flypic fnpack build ``` -成功后会生成 `flypic_x.x.x_all.fpk` 文件。 +成功后会生成 `flypic_0.1.0_all.fpk` 文件。 ## 四、安装应用 @@ -72,7 +65,7 @@ fnpack build ### 方法二:命令行安装 ```bash -fnpack install flypic_x.x.x_all.fpk +appcenter-cli install-fpk flypic_0.1.0_all.fpk ``` ## 五、配置应用 @@ -89,51 +82,102 @@ fnpack install flypic_x.x.x_all.fpk ``` flypic/ +├── ICON.PNG # 应用图标 64x64 +├── ICON_256.PNG # 应用图标 256x256 +├── manifest # 应用清单 ├── app/ -│ ├── server/ # 应用服务器 -│ │ ├── server.js # 主入口 -│ │ ├── package.json -│ │ ├── node_modules/ # 依赖(Docker 构建时包含) -│ │ ├── public/ # 前端静态文件 -│ │ ├── routes/ # API 路由 -│ │ ├── database/ # 数据库模块 -│ │ └── utils/ # 工具函数 +│ ├── server/ # 应用服务器 +│ │ ├── server.js # 主入口 +│ │ ├── package.json # 依赖配置 +│ │ ├── node_modules/ # Linux glibc 依赖 (~57MB) +│ │ │ ├── @img/sharp-linux-x64/ # Sharp 原生模块 +│ │ │ ├── better-sqlite3/ # SQLite 原生模块 +│ │ │ └── ... +│ │ ├── public/ # 前端静态文件 (Vite 构建产物) +│ │ ├── src/ # 后端源码 +│ │ │ ├── routes/ # API 路由 +│ │ │ ├── services/ # 业务逻辑 +│ │ │ ├── models/ # 数据模型 +│ │ │ └── config/ # 配置 +│ │ ├── database/ # 数据库模块 +│ │ └── utils/ # 工具函数 │ └── ui/ -│ ├── config # UI 配置 -│ └── images/ # 应用图标 +│ └── config # UI 入口配置 ├── cmd/ -│ ├── main # 启动脚本 -│ ├── install_init # 安装前脚本 -│ ├── install_callback # 安装后脚本 -│ └── ... # 其他生命周期脚本 -├── wizard/ -│ └── install # 安装向导配置 +│ ├── main # 启动/停止脚本 +│ ├── install_init # 安装前脚本 +│ ├── install_callback # 安装后脚本 +│ ├── uninstall_init # 卸载前脚本 +│ ├── uninstall_callback # 卸载后脚本 +│ ├── upgrade_init # 升级前脚本 +│ ├── upgrade_callback # 升级后脚本 +│ ├── config_init # 配置前脚本 +│ └── config_callback # 配置后脚本 ├── config/ -│ └── resource # 资源配置 -├── manifest # 应用清单 -├── ICON.PNG # 应用图标 256x256 -└── ICON_256.PNG # 应用图标 256x256 +│ ├── privilege # 权限配置 +│ └── resource # 资源配置 (数据共享目录) +└── wizard/ + └── install # 安装向导配置 +``` + +## 关键配置文件 + +### manifest (应用清单) +``` +appname=flypic +version=0.1.0 +desc=飞图 - 专为飞牛 fnOS 设计的轻量、快速、稳定的图像素材检索浏览应用 +arch=x86_64 +display_name=FlyPic +maintainer=ZangXincz +source=thirdparty +service_port=15002 +install_dep_apps=nodejs_v22 +``` + +### config/resource (资源配置) +```json +{ + "data-share": [ + { + "name": "FlyPic数据", + "path": "data", + "mode": "rw", + "desc": "FlyPic 应用数据存储目录" + } + ] +} ``` ## 常见问题 ### Q: 应用启动失败,显示"异常退出" A: 检查以下几点: -1. 确保使用 Docker 构建方法,包含 Linux 版本的 node_modules -2. 检查应用日志,查看具体错误信息 +1. 确保使用 `node scripts/build.js` 构建,包含 Linux glibc 版本的 node_modules +2. 检查应用日志:`/var/apps/flypic/var/info.log` 3. 确保端口 15002 未被占用 +4. 确保依赖应用 nodejs_v22 已安装 + +### Q: Sharp 或 SQLite 报错 +A: 原生模块需要正确的 Linux 版本: +- 必须使用 Docker (node:22-slim, Debian) 构建 +- 不能使用 Alpine 镜像(musl libc 不兼容) +- 不能直接在 Windows/Mac 上 npm install ### Q: 无法访问素材库文件夹 A: 在飞牛应用设置中配置授权目录,添加素材库路径的访问权限。 ### Q: 如何更新应用? A: -1. 重新构建:`node scripts/build-fpk-docker.js` +1. 重新构建:`node scripts/build.js` 2. 上传到飞牛并打包:`fnpack build` 3. 在应用中心选择「更新」或重新安装 ### Q: 如何查看应用日志? -A: 在飞牛系统日志中查看,或 SSH 登录后查看应用日志文件。 +A: SSH 登录后查看: +```bash +cat /var/apps/flypic/var/info.log +``` ## 开发调试 @@ -152,3 +196,10 @@ npm run dev ``` 访问 http://localhost:5173 进行开发调试。 + +## 技术栈 + +- **后端**: Node.js + Express + Sharp + better-sqlite3 + Socket.IO +- **前端**: React + Vite + TailwindCSS + Zustand +- **运行时**: nodejs_v22 (飞牛应用依赖) +- **端口**: 15002