/* storage-file.js —— 桌面端「资料目录」存储底座(2026-11-16) * * 目标:数据不再只躺在 WebView 私有存储里,而是落在一个你指定的普通目录: * <资料目录>/data.json 所有 localStorage 键(设置/提示词/画布/图库索引…) * <资料目录>/images/. 所有图片字节(按内容哈希去重,真实二进制,无 base64) * * 实现要点(为什么能不加异步改造就跑起来): * localStorage 是同步 API,文件 IO 是异步的 ⇒ 启动时一次性把 data.json 读进内存, * 之后读写都是同步的内存操作,写盘走 debounce(800ms)异步刷盘;关窗前 flush 一次。 * * 只在 Tauri 里启用;网页版 enabled() 恒为 false,调用方原样走浏览器存储。 */ ;(function (global) { 'use strict' const PTR_KEY = 'iwb.dataDir' // 资料目录指针:必须住在 WebView 存储里(否则找不到 data.json) const DATA_FILE = 'data.json' const IMG_DIR = 'images' const SCHEMA = 1 let tauri = null let dir = '' let mem = {} // key -> 原始字符串(与 localStorage 一一对应) let assets = {} // key -> { f: 'images/xxx.png', k: 'blob' | 'dataurl' } let small = {} // 小文本 KV(日志等):key -> 字符串 let loaded = false let timer = null let writing = null // 惰性取 __TAURI__:模块加载时它未必已注入,但每个调用点都要能拿到 const tk = () => { if (!tauri) { try { tauri = global.__TAURI__ || null } catch (e) { tauri = null } } return tauri } const fs = () => { const T = tk(); return (T && T.fs) || null } const path = () => { const T = tk(); return (T && T.path) || null } const core = () => { const T = tk(); return (T && T.core) || null } const enabled = () => { const T = tk(); return !!(T && T.core && T.fs && T.path) } const join = async (...p) => { const P = path() if (!P || !P.join) return p.join('/') return await P.join.apply(null, p.map(String)) } const bytes = () => { let n = 0 try { for (const k of Object.keys(mem)) n += (k.length + String(mem[k] || '').length) * 2 } catch (e) { /* ignore */ } return n } const CANVAS_DIR = 'canvases' const WS_PREFIX = 'iwb_ws_' // 长度 7(早期实现误用 slice(9),文件名丢了 2 个字符) const isWsKey = (k) => typeof k === 'string' && k.indexOf(WS_PREFIX) === 0 // 资源库:按分类单独成文件(library/<分类>.json),内容是该键的原始 JSON 文本 // 图片按"来源类别"分二级目录:可读、可分类清理、thumbs 可整体删 const IMG_CAT = { canvas: 'canvas', gallery: 'gallery', thumbs: 'thumbs', legacy: 'legacy' } const catOfKey = (k) => { const key = String(k || '') if (key.indexOf('out_orig_') === 0) return IMG_CAT.gallery if (key.indexOf('out_') === 0) return IMG_CAT.thumbs if (key.indexOf('imgblob_') === 0) return IMG_CAT.canvas if (key.indexOf('http') === 0) return IMG_CAT.legacy // 旧 __cache__ 绝对 URL 键 return IMG_CAT.canvas } const LIB_DIR = 'library' const LIB_FILES = { iwb_web_prompts: 'prompts.json', // 提示词库 iwb_web_groups: 'groups.json', // 节点组 iwb_web_groupgroups: 'group-groups.json', // 节点组的分组树 iwb_web_outputs: 'gallery/index.json', // 图库清单(图片字节仍在 images/gallery/,按 hash 引用) } const libFileOf = (k) => LIB_FILES[k] || '' const dirtyWs = new Set() const removedWs = new Set() const schedule = () => { if (!enabled()) return if (timer) clearTimeout(timer) timer = setTimeout(() => { timer = null; flush().catch(() => {}) }, 800) } const isSplitKey = (k) => isWsKey(k) || !!libFileOf(k) const snapshot = () => { const keys = {} for (const k of Object.keys(mem)) if (!isSplitKey(k)) keys[k] = mem[k] return JSON.stringify({ v: SCHEMA, at: Date.now(), keys, assets, small }) } // 落盘:data.json(不含画布)+ 只重写「脏」画布文件;画布内容本身就是一段合法 JSON const flush = async () => { if (!enabled() || !dir) return false if (writing) return writing const wsDirty = Array.from(dirtyWs) const wsGone = Array.from(removedWs) dirtyWs.clear(); removedWs.clear() const body = snapshot() const target = await join(dir, DATA_FILE) writing = (async () => { try { if (wsDirty.length) { const cdir = await join(dir, CANVAS_DIR) try { await fs().mkdir(cdir, { recursive: true }) } catch (e) { /* 已存在 */ } for (const k of wsDirty) { const text = mem[k] if (text === undefined) continue const abs = await join(cdir, k.slice(WS_PREFIX.length) + '.json') try { const tmp = await join(cdir, k.slice(9) + '.json.tmp') await fs().writeTextFile(tmp, String(text)) await fs().rename(tmp, abs) } catch (e) { try { await fs().writeTextFile(abs, String(text)) } catch (e2) { /* ignore */ } } } } for (const k of wsGone) { try { await fs().remove(await join(dir, CANVAS_DIR, k.slice(WS_PREFIX.length) + '.json')) } catch (e) { /* 不存在就算了 */ } } // 资源库:整体重写分类文件(都很小,改动频繁,不做脏标记) const libKeys = Object.keys(mem).filter((k) => !!libFileOf(k)) if (libKeys.length) { const ldir = await join(dir, LIB_DIR) try { await fs().mkdir(ldir, { recursive: true }) } catch (e) { /* 已存在 */ } for (const k of libKeys) { const rel = libFileOf(k) try { if (rel.indexOf('/') > 0) { const parent = await join(ldir, rel.slice(0, rel.lastIndexOf('/'))) try { await fs().mkdir(parent, { recursive: true }) } catch (e) { /* 已存在 */ } } await fs().writeTextFile(await join(ldir, rel), String(mem[k])) // 新位置写成功后才删旧布局文件,避免"删了但没写上"造成数据丢失 if (rel === 'gallery/index.json') { try { await fs().remove(await join(ldir, 'gallery.json')) } catch (e2) { /* 不存在 */ } } } catch (e) { /* 单个失败不影响其它 */ } } } const tmp2 = await join(dir, DATA_FILE + '.tmp') await fs().writeTextFile(tmp2, body) await fs().rename(tmp2, target) return true } catch (e) { try { await fs().writeTextFile(target, body) } catch (e2) { /* ignore */ } return false } finally { writing = null } })() return writing } // 图片:内容哈希(SHA-256 前 16 位)→ images/.,同图只存一份 const extOf = (mime) => { const m = String(mime || '').toLowerCase() if (m.indexOf('jpeg') >= 0 || m.indexOf('jpg') >= 0) return 'jpg' if (m.indexOf('webp') >= 0) return 'webp' if (m.indexOf('gif') >= 0) return 'gif' if (m.indexOf('svg') >= 0) return 'svg' if (m.indexOf('avif') >= 0) return 'avif' return 'png' } const sha16 = async (buf) => { try { const d = await global.crypto.subtle.digest('SHA-256', buf) return Array.from(new Uint8Array(d)).slice(0, 8).map((b) => b.toString(16).padStart(2, '0')).join('') } catch (e) { let h = 2166136261 const u = new Uint8Array(buf) for (let i = 0; i < u.length; i++) { h ^= u[i]; h = Math.imul(h, 16777619) >>> 0 } return 'f' + (h >>> 0).toString(16) } } const dataUrlToBytes = (s) => { const m = /^data:([^;,]+)?(;base64)?,/i.exec(String(s || '')) if (!m) return null const bin = global.atob(String(s).slice(m[0].length)) const u = new Uint8Array(bin.length) for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i) return { mime: m[1] || 'image/png', bytes: u } } const bytesToDataUrl = (mime, u8) => { let bin = '' const CH = 0x8000 for (let i = 0; i < u8.length; i += CH) bin += String.fromCharCode.apply(null, u8.subarray(i, i + CH)) return 'data:' + (mime || 'image/png') + ';base64,' + global.btoa(bin) } // ── 对外:legacy IndexedDB 同形接口(app.js 的 IDB 就是拿这个)── const kv = { async put(key, value) { try { // 返回对象而不是裸 false:调用方(ImageBlobStore.put)用 r.ok===false 判断失败, // 裸布尔 false 会被误判为成功,产出指向空文件的 {__blob}(v3.25.10 修)。 if (!enabled() || !dir) return { ok: false, error: 'not-ready' } if (value && typeof value === 'object' && typeof value.size === 'number' && value.type !== undefined) { // Blob:直接取二进制落盘 const buf = await value.arrayBuffer() const hash = await sha16(buf) const cat = catOfKey(key) const rel = IMG_DIR + '/' + cat + '/' + hash + '.' + extOf(value.type) const abs = await join(dir, rel) // Windows 全新安装时 images/canvas|gallery 并不存在(只有 thumbs 因为 writeDisplayThumb 会 mkdir), // 直接 writeFile 会失败 → 整条 blob 写入被判失败 → 图片退化成不持久引用。 // 这里先建目录(幂等),与 thumbs 的写法保持一致。 try { await fs().mkdir(await join(dir, IMG_DIR, cat), { recursive: true }) } catch (e) { /* 已存在 */ } await fs().writeFile(abs, new Uint8Array(buf)) assets[String(key)] = { f: rel, k: 'blob', m: value.type || 'application/octet-stream' } schedule() // 立即落盘:登记表只存在 data.json 里,晚 800ms 就可能被强杀丢掉, // 而画布文件是即时写的 ⇒ 引用还在、登记没了,GC 会把在用图片当孤儿。 await flush() try { global.IWBGalleryAudit && global.IWBGalleryAudit.noteWrite(key, true) } catch (e) { /* 计数失败不影响写入 */ } return true } const s = String(value) if (s.indexOf('data:') === 0) { const dec = dataUrlToBytes(s) if (dec) { const hash = await sha16(dec.bytes) const cat2 = catOfKey(key) const rel = IMG_DIR + '/' + cat2 + '/' + hash + '.' + extOf(dec.mime) const abs = await join(dir, rel) try { await fs().mkdir(await join(dir, IMG_DIR, cat2), { recursive: true }) } catch (e) { /* 已存在 */ } await fs().writeFile(abs, dec.bytes) assets[String(key)] = { f: rel, k: 'dataurl', m: dec.mime } schedule() await flush() try { global.IWBGalleryAudit && global.IWBGalleryAudit.noteWrite(key, true) } catch (e) { /* 计数失败不影响写入 */ } return true } } small[String(key)] = s schedule() return true } catch (e) { try { global.IWBMetricsSwallow && global.IWBMetricsSwallow('file-kv-put', e) } catch (e2) { /* ignore */ } try { global.IWBGalleryAudit && global.IWBGalleryAudit.noteWrite(key, false, e) } catch (e2) { /* ignore */ } return { ok: false, error: String((e && e.message) || e) } } }, async get(key) { try { const a = assets[String(key)] if (a) { const abs = await join(dir, a.f) const u8 = await fs().readFile(abs) if (a.k === 'dataurl') return bytesToDataUrl(a.m, u8) return new Blob([u8], { type: a.m || 'application/octet-stream' }) } return Object.prototype.hasOwnProperty.call(small, String(key)) ? small[String(key)] : null } catch (e) { return null } }, async getBlob(key) { try { const a = assets[String(key)] if (!a) return null const abs = await join(dir, a.f) const u8 = await fs().readFile(abs) return new Blob([u8], { type: a.m || 'application/octet-stream' }) } catch (e) { return null } }, async del(key) { try { const k = String(key) const had = !!assets[k] || Object.prototype.hasOwnProperty.call(small, k) delete assets[k]; delete small[k] schedule() return had } catch (e) { return false } }, async keys() { try { return Object.keys(assets).concat(Object.keys(small)) } catch (e) { return [] } }, async logPut(id, entry) { return kv.put('log:' + id, JSON.stringify(entry)) }, async logAll() { const out = [] for (const k of Object.keys(small)) if (k.indexOf('log:') === 0) { try { out.push(JSON.parse(small[k])) } catch (e) { /* ignore */ } } return out }, async kvGet(key) { return kv.get(key) }, async kvPut(key, value) { return kv.put(key, typeof value === 'string' ? value : JSON.stringify(value)) }, } // ── 对外:localStorage 同形的内存表(供 IWBStorageLocal / lsGet 使用)── const storage = { getItem(k) { return Object.prototype.hasOwnProperty.call(mem, String(k)) ? mem[String(k)] : null }, setItem(k, v) { const key = String(k) mem[key] = String(v) if (isWsKey(key)) { removedWs.delete(key); dirtyWs.add(key) } schedule() }, removeItem(k) { const key = String(k) delete mem[key] if (isWsKey(key)) { dirtyWs.delete(key); removedWs.add(key) } schedule() }, clear() { mem = {}; schedule() }, key(i) { return Object.keys(mem)[i] || null }, get length() { return Object.keys(mem).length }, } const runtime = { get(key, fallback) { try { const v = storage.getItem(key); return v === null ? fallback : JSON.parse(v) } catch (e) { return fallback } }, set(key, value) { try { storage.setItem(key, JSON.stringify(value)); return true } catch (e) { return false } }, remove(key) { try { storage.removeItem(key); return true } catch (e) { return false } }, rawGet(key, fallback) { const v = storage.getItem(key); return v === null ? fallback : v }, rawSet(key, value) { try { storage.setItem(key, String(value)); return true } catch (e) { return false } }, bytes, indexedDb: kv, } // v2 迁移:把平铺的 images/xxx.png 按「来源类别」移进 images// async function migrateV2() { try { const marker = await join(dir, 'migrated-v2.flag') if (await fs().exists(marker)) return 0 let moved = 0 for (const key of Object.keys(assets)) { const a = assets[key] if (!a || !a.f) continue const parts = String(a.f).split('/') if (parts.length !== 2 || parts[0] !== IMG_DIR) continue // 已经在分类目录里 const cat = catOfKey(key) const rel = IMG_DIR + '/' + cat + '/' + parts[1] try { const cdir = await join(dir, IMG_DIR, cat) try { await fs().mkdir(cdir, { recursive: true }) } catch (e) { /* 已存在 */ } await fs().rename(await join(dir, a.f), await join(dir, rel)) a.f = rel moved++ } catch (e) { /* 单张失败保留原路径,下次再试 */ } } await flush() await fs().writeTextFile(marker, String(moved)) return moved } catch (e) { return 0 } } // 一次性:给图库清单里缺 data 的条目回填缩略图(图库渲染读 f.data || f.url) async function backfillGalleryThumbs() { try { const marker = await join(dir, 'gallery-thumbs.flag') if (await fs().exists(marker)) return 0 const raw = mem['iwb_web_outputs'] if (!raw) return 0 const items = JSON.parse(raw) if (!Array.isArray(items)) return 0 let n = 0 for (const it of items) { if (!it || it.data) continue const a = assets[it.idb] if (!a || !a.f) continue try { const u8 = await fs().readFile(await join(dir, a.f)) if (!u8 || u8.length > 96 * 1024) continue const hash = String(a.f).split('/').pop().replace(/\.[^.]+$/, '') const thumbPath = await join(dir, IMG_DIR, 'thumbs', hash + '.jpg') try { if (!(await fs().exists(thumbPath))) await fs().writeFile(thumbPath, u8) } catch (e) { /* 写失败不阻塞 */ } it.thumbHash = hash it.data = '' n++ } catch (e) { /* 单张失败忽略 */ } } if (n) { mem['iwb_web_outputs'] = JSON.stringify(items); await flush() } await fs().writeTextFile(marker, String(n)) return n } catch (e) { return 0 } } // 修复(一次性):早期版本用 slice(9) 生成文件名,丢了 id 前 2 个字符("ws") // ⇒ 读每个文件内容里的 id,把文件名改回 .json,键才能和画布对上。 async function repairCanvasFileNames() { try { const marker = await join(dir, 'canvases-fixed.flag') if (await fs().exists(marker)) return 0 const cdir = await join(dir, CANVAS_DIR) const entries = await fs().readDir(cdir) let n = 0 for (const e of entries) { if (!e || e.isDirectory || !/\.json$/.test(e.name)) continue try { const txt = await fs().readTextFile(await join(cdir, e.name)) let id = '' try { const j = JSON.parse(txt); id = String((j && j.id) || '') } catch (err) { id = '' } const base = e.name.replace(/\.json$/, '') const want = id ? (id.indexOf('ws') === 0 ? id : 'ws' + id) : 'ws' + base const target = want + '.json' if (target !== e.name) { await fs().rename(await join(cdir, e.name), await join(cdir, target)) n++ } } catch (err) { /* 单个失败跳过 */ } } await fs().writeTextFile(marker, String(n)) return n } catch (e) { return 0 } } // 恢复(一次性):WebView 的 localStorage 里还留着迁移前的原始数据(迁移只是"复制进文件", // 从未清过 localStorage)。凡文件里节点更少的画布,就用 localStorage 的版本覆盖回来。 async function recoverFromWebStorage() { try { const marker = await join(dir, 'recovered-from-browser.flag') if (await fs().exists(marker)) return 0 let n = 0 const ls = global.localStorage for (let i = 0; i < ls.length; i++) { const k = ls.key(i) if (!k || k.indexOf(WS_PREFIX) !== 0) continue const raw = ls.getItem(k) if (!raw) continue let js = null try { js = JSON.parse(raw) } catch (e) { continue } const lsNodes = (js && js.nodes) || [] if (!lsNodes.length) continue let cur = null try { cur = JSON.parse(mem[k] || 'null') } catch (e) { cur = null } const curNodes = (cur && cur.nodes) || [] if (curNodes.length >= lsNodes.length) continue mem[k] = raw dirtyWs.add(k) n++ } if (n) { await flush(); await blog('recover:from-browser ' + n) } await fs().writeTextFile(marker, String(n)) return n } catch (e) { return 0 } } // ---- 插件外置(P1):<资料目录>/plugins/ 覆盖随包的内置插件 ---- const PLUG_DIR = 'plugins' async function pluginManifest() { try { const txt = await fs().readTextFile(await join(dir, PLUG_DIR, 'index.json')) const j = JSON.parse(txt) return Array.isArray(j) ? j : (Array.isArray(j && j.plugins) ? j.plugins : []) } catch (e) { return [] } } async function pluginRead(file) { const safe = String(file || '') if (!/^[A-Za-z0-9._-]+$/.test(safe)) throw new Error('非法插件文件名') return fs().readTextFile(await join(dir, PLUG_DIR, safe)) } async function pluginWrite(file, text) { const safe = String(file || '') if (!/^[A-Za-z0-9._-]+$/.test(safe)) throw new Error('非法插件文件名') await pluginDir() await fs().writeTextFile(await join(dir, PLUG_DIR, safe), String(text)) return true } async function pluginRemove(file) { const safe = String(file || '') if (!/^[A-Za-z0-9._-]+$/.test(safe)) throw new Error('非法插件文件名') try { await fs().remove(await join(dir, PLUG_DIR, safe)); return true } catch (e) { return false } } // 开发者模式:<资料目录>/plugins/local//plugin.js(未签名,只在开关打开时加载) async function pluginListLocal() { try { const ldir = await join(dir, PLUG_DIR, 'local') const entries = await fs().readDir(ldir) const out = [] for (const e of entries) { if (!e || !e.isDirectory) continue try { const code = await fs().readTextFile(await join(ldir, e.name, 'plugin.js')) out.push({ id: e.name, file: 'local/' + e.name + '/plugin.js', code: code }) } catch (err) { /* 该目录没有 plugin.js,跳过 */ } } return out } catch (e) { return [] } } async function pluginDir() { const p = await join(dir, PLUG_DIR) try { await fs().mkdir(p, { recursive: true }) } catch (e) { /* 已存在 */ } return p } // ---- 目录插件(v3.25.41 / M1):<资料目录>/plugins//{manifest.json,main.js,styles.css,…} ---- // 路径一律按「段」校验,禁绝对路径与 ..(防目录穿越);单文件读写沿用上面的 read/write。 function safePluginRel(rel) { const parts = String(rel || '').split('/') if (!parts.length || parts.length > 6) throw new Error('非法插件路径') for (const seg of parts) { if (!seg || !/^[A-Za-z0-9._-]+$/.test(seg) || seg === '.' || seg === '..') throw new Error('非法插件路径') } return parts.join('/') } async function pluginRoot() { const p = await pluginDir() try { await fs().mkdir(p, { recursive: true }) } catch (e) { /* 已存在 */ } return p } async function pluginFilePath(rel) { return join(await pluginRoot(), safePluginRel(rel)) } // 扫描 /* 的目录(不递归),只返回目录名,是否是真插件由调用方读 manifest 判断 async function pluginListDirs() { try { const root = await pluginRoot() const entries = await fs().readDir(root) return entries.filter((e) => e && e.isDirectory && /^[A-Za-z0-9][A-Za-z0-9._-]{1,63}$/.test(e.name)).map((e) => ({ id: e.name })) } catch (e) { return [] } } async function pluginReadFile(rel) { return fs().readTextFile(await pluginFilePath(rel)) } async function pluginWriteFile(rel, text) { const abs = await pluginFilePath(rel) const segs = safePluginRel(rel).split('/') if (segs.length > 1) { const parent = await join(await pluginRoot(), segs.slice(0, -1).join('/')) try { await fs().mkdir(parent, { recursive: true }) } catch (e) { /* 已存在 */ } } await fs().writeTextFile(abs, String(text)) return true } async function pluginWriteBinary(rel, bytes) { const abs = await pluginFilePath(rel) const segs = safePluginRel(rel).split('/') if (segs.length > 1) { const parent = await join(await pluginRoot(), segs.slice(0, -1).join('/')) try { await fs().mkdir(parent, { recursive: true }) } catch (e) { /* 已存在 */ } } await fs().writeFile(abs, new Uint8Array(bytes)) return true } async function pluginMkdir(rel) { const abs = await pluginFilePath(rel) await fs().mkdir(abs, { recursive: true }) return true } // 重命名插件目录(单级,用于安装时的原子替换) async function pluginRenameDir(fromId, toId) { const a = safePluginRel(fromId) const b = safePluginRel(toId) if (a.indexOf('/') >= 0 || b.indexOf('/') >= 0) throw new Error('只允许重命名一级插件目录') await fs().rename(await join(await pluginRoot(), a), await join(await pluginRoot(), b)) return true } async function pluginExistsDir(id) { try { return await fs().exists(await join(await pluginRoot(), safePluginRel(id))) } catch (e) { return false } } // 删除插件目录(递归)。只允许一级 ,避免误删 plugins 根或上级目录。 async function pluginRemoveDir(id) { const seg = safePluginRel(id) if (seg.indexOf('/') >= 0) throw new Error('只允许删除一级插件目录') await fs().remove(await join(await pluginRoot(), seg), { recursive: true }) return true } // ---- 插件数据(v3.25.42 / M2):<资料目录>/plugin-data/.json ---- // 与插件**代码目录**分离:卸载插件默认保留数据;写入用 tmp + rename,避免半截 JSON。 const PDATA_DIR = 'plugin-data' async function pluginDataDir() { const p = await join(dir, PDATA_DIR) try { await fs().mkdir(p, { recursive: true }) } catch (e) { /* 已存在 */ } return p } function safePluginId(id) { const s0 = String(id || '') if (!/^[A-Za-z0-9][A-Za-z0-9._-]{1,63}$/.test(s0)) throw new Error('非法插件 id') return s0 } async function pluginDataRead(id) { try { return await fs().readTextFile(await join(await pluginDataDir(), safePluginId(id) + '.json')) } catch (e) { return null } } async function pluginDataWrite(id, text) { const dir0 = await pluginDataDir() const target = await join(dir0, safePluginId(id) + '.json') const tmp = await join(dir0, safePluginId(id) + '.json.tmp') await fs().writeTextFile(tmp, String(text)) try { await fs().rename(tmp, target) } catch (e) { try { await fs().remove(target) } catch (e2) { /* 不存在 */ } await fs().rename(tmp, target) } return true } async function pluginDataRemove(id) { try { await fs().remove(await join(await pluginDataDir(), safePluginId(id) + '.json')); return true } catch (e) { return false } } async function pluginDataList() { try { const entries = await fs().readDir(await pluginDataDir()) return entries.filter((e) => e && !e.isDirectory && /\.json$/.test(e.name)).map((e) => ({ id: e.name.replace(/\.json$/, '') })) } catch (e) { return [] } } // ---- 插件文件(v3.26.36):<资料目录>/plugin-data//files/ ---- // 与插件 JSON 数据分离:文件放目录、JSON 只存文件名(内容哈希命名)。 // 安全:文件名白名单(禁路径分隔/点段)、单文件 8MB、单插件总量 64MB、原子写。 const PFILE_DIR = 'files' const PFILE_MAX = 8 * 1024 * 1024 const PFILE_TOTAL = 64 * 1024 * 1024 const PFILE_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,63}\.(jpg|jpeg|png|webp)$/i function pluginFileNameOk (name) { const P = global.IWBPluginFilesPolicy if (P && typeof P.fileOk === 'function') return P.fileOk(name) const s0 = String(name || '') if (!PFILE_NAME_RE.test(s0)) return false if (s0.indexOf('..') >= 0 || s0.indexOf('/') >= 0 || s0.indexOf(String.fromCharCode(92)) >= 0) return false return true } async function pluginFilesDir (id) { const p = await join(await pluginDataDir(), safePluginId(id), PFILE_DIR) try { await fs().mkdir(p, { recursive: true }) } catch (e) { /* 已存在 */ } return p } async function pluginFilePut (id, name, dataUrl) { try { if (!pluginFileNameOk(name)) return { ok: false, error: '非法文件名(只允许小写字母/数字/-/_ + jpg/png/webp)' } const decoded = dataUrlToBytes(String(dataUrl || '')) const bytes = decoded && decoded.bytes if (!bytes || !bytes.length) return { ok: false, error: '图片数据为空' } const stat = await pluginFileStat(id) const existing = stat.files.find((f) => f.name === name) const P = global.IWBPluginFilesPolicy const q = P ? P.quotaOk(stat.bytes, bytes.length, existing ? existing.size : 0) : null if (q && !q.ok) { if (q.reason === 'file-too-large') return { ok: false, error: '单张图片超过 8MB' } if (q.reason === 'total-too-large') return { ok: false, error: '插件数据总量超过 64MB,请先清理' } return { ok: false, error: '图片数据为空' } } if (!P) { if (bytes.length > PFILE_MAX) return { ok: false, error: '单张图片超过 8MB' } if (stat.bytes - (existing ? existing.size : 0) + bytes.length > PFILE_TOTAL) return { ok: false, error: '插件数据总量超过 64MB,请先清理' } } const dir0 = await pluginFilesDir(id) const target = await join(dir0, name) const tmp = target + '.tmp' await fs().writeFile(tmp, bytes) try { await fs().rename(tmp, target) } catch (e) { try { await fs().remove(target) } catch (e2) { /* ignore */ } await fs().rename(tmp, target) } return { ok: true, name: name, size: bytes.length } } catch (e) { return { ok: false, error: String((e && e.message) || e) } } } async function pluginFileGet (id, name) { try { if (!pluginFileNameOk(name)) return { ok: false, error: '非法文件名' } const u8 = await fs().readFile(await join(await pluginFilesDir(id), name)) if (!u8 || !u8.length) return { ok: false, error: '文件不存在' } return { ok: true, url: bytesToDataUrl(sniffMime(u8) || 'image/jpeg', u8), size: u8.length } } catch (e) { return { ok: false, error: '文件不存在' } } } async function pluginFileList (id) { try { const entries = await fs().readDir(await pluginFilesDir(id)) const out = [] for (const e of entries) { if (!e || e.isDirectory || !pluginFileNameOk(e.name)) continue let size = 0 try { const u8 = await fs().readFile(await join(await pluginFilesDir(id), e.name)); size = u8 ? u8.length : 0 } catch (err) { size = 0 } out.push({ name: e.name, size: size }) } out.sort((a, b) => a.name.localeCompare(b.name)) return out } catch (e) { return [] } } async function pluginFileRemove (id, name) { try { if (!pluginFileNameOk(name)) return { ok: false, error: '非法文件名' } await fs().remove(await join(await pluginFilesDir(id), name)) return { ok: true } } catch (e) { return { ok: false, error: '删除失败' } } } async function pluginFileStat (id) { try { const files = await pluginFileList(id) return { ok: true, files: files, bytes: files.reduce((n, f) => n + (f.size || 0), 0), count: files.length } } catch (e) { return { ok: false, files: [], bytes: 0, count: 0 } } } // 备份用(v3.26.59):读原始字节,ZIP 直接写字节 —— 不做 dataURL 往返,省掉 33% 的 base64 膨胀。 async function pluginFileReadBytes (id, name) { try { if (!pluginFileNameOk(name)) return null const u8 = await fs().readFile(await join(await pluginFilesDir(id), name)) return (u8 && u8.length) ? u8 : null } catch (e) { return null } } // 备份用:枚举「所有插件」的插件文件(plugin-data//files/)。 // 不调 pluginFilesDir(那个会 mkdir):没有 files 目录的插件直接跳过。 async function pluginFilesListAll () { const out = [] let entries = [] try { entries = await fs().readDir(await pluginDataDir()) } catch (e) { return out } for (const e of entries) { if (!e || !e.isDirectory) continue const id = String(e.name || '') if (!/^[A-Za-z0-9][A-Za-z0-9._-]{1,63}$/.test(id)) continue let fe = [] try { fe = await fs().readDir(await join(await pluginDataDir(), id, PFILE_DIR)) } catch (err) { continue } const files = [] for (const f of fe) { if (!f || f.isDirectory || !pluginFileNameOk(f.name)) continue let size = 0 try { const u8 = await fs().readFile(await join(await pluginDataDir(), id, PFILE_DIR, f.name)); size = u8 ? u8.length : 0 } catch (err2) { size = 0 } files.push({ name: f.name, size: size }) } if (files.length) { files.sort((a, b) => a.name.localeCompare(b.name)); out.push({ id: id, files: files }) } } return out } // 启动加载进度(v3.26.109):局域网资料目录下这里就是最慢的一段,按文件数上报真实百分比 const bp = () => (typeof global !== 'undefined' && global.IWBBootProgress) || null const bpReport = (phase, done, total, detail) => { const b = bp(); if (b) b.report(phase, done, total, detail) } async function loadInto() { // data.json 不存在 ⇒ 把当前 WebView 里的数据迁过去(只做一次) const target = await join(dir, DATA_FILE) bpReport('prepare', 1, 1) let parsed = null try { const txt = await fs().readTextFile(target); parsed = JSON.parse(txt) } catch (e) { parsed = null } bpReport('data', 1, 1) const fromDataJson = !!(parsed && parsed.keys) if (fromDataJson) { mem = parsed.keys || {} assets = parsed.assets || {} small = parsed.small || {} } else { mem = {} try { for (let i = 0; i < global.localStorage.length; i++) { const k = global.localStorage.key(i) if (k) mem[k] = global.localStorage.getItem(k) } } catch (e) { /* ignore */ } } // 画布:一张画布一个文件(canvases/.json,内容就是该键的原始 JSON) try { const cdir = await join(dir, CANVAS_DIR) try { await fs().mkdir(cdir, { recursive: true }) } catch (e) { /* 已存在 */ } const entries = await fs().readDir(cdir) const wsFiles = entries.filter((e) => e && !e.isDirectory && /\.json$/.test(e.name)) bpReport('canvases', 0, wsFiles.length) let wsRead = 0 for (const e of wsFiles) { try { const text = await fs().readTextFile(await join(cdir, e.name)) mem['iwb_ws_' + e.name.replace(/\.json$/, '')] = text } catch (e) { /* 单个画布读失败不影响其它 */ } wsRead++ bpReport('canvases', wsRead, wsFiles.length) } } catch (e) { /* 目录还没有 */ } // 资源库分类文件(library/*.json):文件比 data.json 新,直接覆盖同名键 try { const ldir = await join(dir, LIB_DIR) const libKeys = Object.keys(LIB_FILES) let libDone = 0 for (const key of libKeys) { try { mem[key] = await fs().readTextFile(await join(ldir, LIB_FILES[key])) } catch (err) { // 兼容旧布局:library/gallery.json(平铺);读到就沿用,flush 会写到新位置 if (key === 'iwb_web_outputs') { try { mem[key] = await fs().readTextFile(await join(ldir, 'gallery.json')) } catch (err2) { /* 也没有 */ } } } libDone++ bpReport('library', libDone, libKeys.length) } } catch (e) { /* 目录还没有 */ } // 旧格式:画布还压在 data.json 里 ⇒ 标脏,下一次 flush 拆成单文件 if (fromDataJson) for (const k of Object.keys(parsed.keys || {})) if (isWsKey(k)) dirtyWs.add(k) return fromDataJson ? 'loaded' : 'migrated' } // 一次性迁移:把老版本存在 IndexedDB 里的图片字节搬到 images/ 下(跑过一次就写标记文件) // 启动日志:超过 256KB 只保留最后 64KB(否则长年累月会一直长) const blog = async (m) => { try { const logPath = await join(dir, '_boot.log') let tail = '' try { const st = await fs().stat(logPath) if (st && st.size > 262144) { const txt = await fs().readTextFile(logPath) tail = txt.slice(-65536) } } catch (e) { /* 文件不存在就是首次 */ } const line = new Date().toISOString() + ' ' + m + '\n' if (tail) await fs().writeTextFile(logPath, tail + line) else await fs().writeTextFile(logPath, line, { append: true }) } catch (e) { /* ignore */ } } // 首屏之后再做的一次性维护:延迟到渲染之后,别和启动抢 I/O const deferAfterPaint = (fn) => { const run = () => { try { Promise.resolve(fn()).catch(() => {}) } catch (e) { /* ignore */ } } try { if (typeof setTimeout === 'function') setTimeout(run, 1200); else run() } catch (e) { run() } } async function migrateBlobs() { try { await blog('migrate:start dir=' + dir) // 注意:Tauri fs 默认禁dotfile(.xxx),标记文件用普通名字 const marker = await join(dir, 'migrated.flag') const has = await fs().exists(marker) await blog('migrate:marker exists=' + has) if (has) return 0 const C = global.IWBStorageContract || {} const store = (global.IWBStorageIndexedDB && global.IWBStorageIndexedDB.create) ? global.IWBStorageIndexedDB.create({ contract: C.indexedDb }) : null await blog('migrate:store=' + !!store + ' imagesAll=' + !!(store && store.imagesAll)) if (!store || typeof store.imagesAll !== 'function') { await fs().writeTextFile(marker, 'no-idb'); return 0 } const r = await store.imagesAll() await blog('migrate:result ok=' + (r && r.ok) + ' n=' + (r && r.value && r.value.length)) const list = (r && r.ok && Array.isArray(r.value)) ? r.value : [] let n = 0 for (const it of list) { if (!it || it.key === undefined) continue try { if (await kv.put(it.key, it.value)) n++ } catch (e) { /* 单条失败不影响其它 */ } } await flush() await fs().writeTextFile(marker, String(n)) await blog('migrate:done n=' + n) return n } catch (e) { await blog('migrate:ERR ' + (e && (e.message || e))); return 0 } } // 选目录(系统目录选择器)。返回绝对路径,取消返回 ''。 async function pickDir() { const T = tk() const open = T && T.dialog && T.dialog.open if (!open) throw new Error('系统目录选择器不可用') const r = await open({ directory: true, multiple: false, title: '选择资料目录' }) return r ? String(r) : '' } // 首次启动:让用户选「默认目录」还是「已有目录」,避免新装就写到一个他不知道的地方 function askFirstDir(defaultDir) { return new Promise((resolve) => { try { const mask = document.createElement('div') // 这个弹窗在首启动、主题 CSS 可能尚未生效时就要显示,所以每个 var() 都带字面兜底: // token 缺席时退化成本版改动前的样子(白底深字),而不是透明盒子。 mask.style.cssText = 'position:fixed;inset:0;z-index:var(--iwb-z-alert,4000);' // 遮罩色是全仓唯一没有 token 的表面色(.iwb-modal-mask / .iwb-command-mask 也各写了一份 rgba)。 // 它既不是 bg 也不是 panel,硬凑会让亮色主题出现「浅色遮罩」。留给 RFC 决定 --iwb-scrim // 的取值与消费者(现有 3 处),在此之前登记为例外,不让它悄悄变成永久的裸值。 + 'background:rgba(18,20,26,.72) /*iwb:raw-until=3.28.0*/;' + 'display:flex;align-items:center;justify-content:center;' + 'font-family:-apple-system,BlinkMacSystemFont,"PingFang SC",sans-serif;' + 'font-size:var(--iwb-font-md,14px);line-height:1.6' const box = document.createElement('div') box.style.cssText = 'background:var(--iwb-panel,#fff);color:var(--iwb-text,#111);' + 'border-radius:var(--iwb-radius-popover,14px);padding:var(--iwb-space-24,24px);' + 'max-width:580px;box-shadow:var(--iwb-elevation-4,0 24px 60px rgba(0,0,0,.35))' const btn = (t, primary) => { const b = document.createElement('button') b.textContent = t b.style.cssText = 'padding:var(--iwb-space-8,8px) var(--iwb-space-16,16px);' + 'border-radius:var(--iwb-radius-control,8px);font-size:var(--iwb-font-md,13px);cursor:pointer;' + 'border:1px solid ' + (primary ? 'var(--iwb-brand,#2563eb)' : 'var(--iwb-border,#d0d4dc)') + ';' + 'background:' + (primary ? 'var(--iwb-brand,#2563eb)' : 'var(--iwb-panel,#fff)') + ';' + 'color:' + (primary ? 'var(--iwb-on-brand,#fff)' : 'var(--iwb-text,#111)') return b } box.innerHTML = '
首次启动:选择资料目录
' + '
设置、提示词、画布和所有图片都会存在这个目录里。
' + '
换机器/重装时,把目录指到旧的资料目录就能直接继续用。
' + '
默认位置:' + defaultDir + '
' const row = document.createElement('div') row.style.cssText = 'display:flex;gap:var(--iwb-space-10,10px);justify-content:flex-end' const bDefault = btn('用默认目录', true) const bPick = btn('选择已有目录…', false) const done = (v) => { try { mask.remove() } catch (e) { /* ignore */ } resolve(v) } bDefault.onclick = () => done(defaultDir) bPick.onclick = async () => { try { const p = await pickDir(); done(p || defaultDir) } catch (e) { done(defaultDir) } } row.appendChild(bPick); row.appendChild(bDefault) box.appendChild(row) mask.appendChild(box) document.body.appendChild(mask) } catch (e) { resolve(defaultDir) } }) } // 切换资料目录:先把当前内存刷盘,再改指针并重载窗口(重载后从新目录装载) // 转移:把整个资料目录复制到新位置,成功后切换指针并重载(原目录保留,由用户自行删除) async function migrateTo(next) { const target = String(next || '') if (!target || target === dir) return false await flush() const invoke = core().invoke if (!invoke) throw new Error('Tauri 不可用') await invoke('copy_tree', { src: dir, dst: target }) try { global.localStorage.setItem(PTR_KEY, target) } catch (e) { /* ignore */ } try { global.location.reload() } catch (e) { /* ignore */ } return true } async function switchTo(next) { const target = String(next || '') if (!target) return false await flush() try { global.localStorage.setItem(PTR_KEY, target) } catch (e) { /* ignore */ } try { global.location.reload() } catch (e) { /* ignore */ } return true } /* 建立工作必需目录:canvases/ library/ plugins/ trash/ 与 images/{canvas,gallery,thumbs,legacy} */ async function ensureDirs() { const subs = [CANVAS_DIR, 'library', PLUG_DIR, 'trash', IMG_DIR, IMG_DIR + '/canvas', IMG_DIR + '/gallery', IMG_DIR + '/thumbs', IMG_DIR + '/legacy'] // v3.26.109:串行建 9 个目录 = 9 次网络往返(局域网资料目录上就是启动白屏的主因之一), // 改成并发:一次往返的量级。mkdir recursive 本来幂等,并发安全。 await Promise.all(subs.map((sub) => join(dir, sub).then((abs) => fs().mkdir(abs, { recursive: true })).catch(() => {}))) return true } async function init(opts) { const o = opts || {} tauri = global.__TAURI__ || null if (!enabled()) return false if (loaded) return true let want = o.dir || '' let hasPointer = false try { want = want || global.localStorage.getItem(PTR_KEY) || ''; hasPointer = !!want } catch (e) { /* ignore */ } if (!want) { // 默认目录:~/Documents/ImageWorkbench let def = '' try { const doc = await path().documentDir(); def = await join(doc, 'ImageWorkbench') } catch (e) { def = '' } // 首次启动(没有指针)⇒ 让用户选默认目录或已有目录 if (!hasPointer && o.wizard !== false && def) { try { want = await askFirstDir(def) } catch (e) { want = def } } else { want = def } } if (!want) return false // 授权(fs scope 是运行时授权,重启后由这里补一次) try { await core().invoke('grant_dir', { dir: want }) } catch (e) { console.error('[iwb][file-store] 授权失败', e); return false } dir = want bpReport('prepare', 1, 4, '资料目录已授权') try { global.localStorage.setItem(PTR_KEY, dir) } catch (e) { /* ignore */ } try { await fs().mkdir(await join(dir, IMG_DIR), { recursive: true }) } catch (e) { /* 已存在 */ } // 兜底:把工作必需的子目录一次性补齐(幂等)。 // 为什么需要:Windows 全新安装时 images/ 下只有 thumbs/,缺了 canvas/ 会导致 // 图片写入失败(历史 bug:写进不持久的 Cache → 重启丢图);目录被手工删掉时也靠这里自愈, // 否则启动阶段读目录抛错会直接影响首屏渲染。 bpReport('prepare', 2, 4, '补齐子目录') try { await ensureDirs() } catch (e) { /* 建目录失败不阻塞启动 */ } bpReport('prepare', 3, 4, '整理画布文件名') try { await repairCanvasFileNames() } catch (e) { /* 修复失败按原样装载 */ } bpReport('prepare', 4, 4) await loadInto() // 从 WebView 的 localStorage 捞回被截断/覆盖的画布(一次性) try { await recoverFromWebStorage() } catch (e) { /* 忽略 */ } loaded = true bpReport('finalize', 1, 1) // 首次迁移要立刻落盘,别等 debounce await flush() // v3.26.109:以下都是一次性维护(各自带标记文件,正常只是 check 一下),但每次都要若干次 // 网络往返。放到首屏渲染之后跑,局域网资料目录的启动时间能少好几秒。 deferAfterPaint(async () => { // 老版本图片在 IndexedDB 里 ⇒ 搬到 images/(带标记,只跑一次) try { await migrateBlobs() } catch (e) { /* 迁移失败不阻塞启动 */ } // 图库清单补齐缩略图(一次性) try { await backfillGalleryThumbs() } catch (e) { /* 忽略 */ } // 图库清单去 base64(一次性):缩略图已在 images/thumbs/,清单只留 thumbHash try { await stripInlineGalleryThumbs() } catch (e) { /* 忽略 */ } // trash/ 轮转:gcImages 只是移进来,超过 30 天在这里真正删除 try { await rotateTrash(30) } catch (e) { /* 忽略 */ } // 旧的 768px 显示缩略图一次性清理(缓存可再生) try { const dropped = await dropLegacyDisplayThumbs(); if (dropped) console.info('[iwb][file-store] 清理旧缩略图', dropped, '个') } catch (e) { /* 忽略 */ } }) // 自愈:图库清单丢了但 assets 还有 out_ 键 ⇒ 按键重建(名称/时间/idb 可推,label/远程 url 无法恢复) try { if (mem['iwb_web_outputs'] === undefined) { const names = [] for (const k of Object.keys(assets)) { if (k.indexOf('out_orig_') === 0) names.push(k.slice(9)) else if (k.indexOf('out_') === 0) names.push(k.slice(4)) } const uniq = Array.from(new Set(names)) if (uniq.length) { const items = uniq.map((name) => { const m = /(\d{13})/.exec(name) const orig = 'out_orig_' + name return { name: name, url: '', size: 0, data: '', thumbHash: '', mtime: m ? Number(m[1]) : Date.now(), w: 0, h: 0, label: '', idb: 'out_' + name, origIdb: Object.prototype.hasOwnProperty.call(assets, orig) ? orig : undefined, } }) items.sort((a, b) => a.mtime - b.mtime) // 关键:把缩略图字节回填到清单的 data 字段(图库渲染读 f.data || f.url)。 // 只回填小于 96KB 的缩略图,避免清单膨胀。 for (const it of items) { const a = assets[it.idb] if (!a || !a.f) continue try { const u8 = await fs().readFile(await join(dir, a.f)) if (!u8 || u8.length > 96 * 1024) continue it.data = bytesToDataUrl(a.m || 'image/jpeg', u8) it.thumbHash = String(a.f).split('/').pop().replace(/\.[^.]+$/, '') } catch (e) { /* 单张失败不影响其它 */ } } mem['iwb_web_outputs'] = JSON.stringify(items) await flush() await blog('gallery:rebuilt ' + items.length) } } } catch (e) { /* 自愈失败不影响启动 */ } // 平铺图片 → 二级分类目录(一次性) try { await migrateV2() } catch (e) { /* 迁移失败不阻塞启动 */ } // 「点下载直接落盘」要求下载目录在本次运行里也被授权(fs scope 是会话级的) try { const rawDl = global.localStorage.getItem('iwb.downloadDir') const dl = rawDl ? JSON.parse(rawDl) : '' if (dl) { try { await core().invoke('grant_dir', { dir: String(dl), record: false }) } catch (e) { /* 忽略 */ } } } catch (e) { /* 下载目录指针不存在或格式异常 */ } return true } // 清理未引用图片:只动「没有任何 assets 条目指向」的文件,移到 trash/(不直接删)。 // 保守策略:assets 里还有登记的键一律保留,避免误删仍在画布上引用的图。 // v3.26.34(一次性):清掉旧的 768px 显示缩略图。 // 为什么:旧编码 768px/WebP 0.86,单张 500~900KB,49 张就 24MB(比原图还大)。 // 显示缩略图是**可再生缓存**(打开画布时按需重建),删掉不会丢任何用户数据; // 只删 `*_768.*`,保留图库缩略图(无 _768 后缀、需要清单引用,不能删)。 async function dropLegacyDisplayThumbs() { try { if (!enabled() || !dir) return 0 const marker = await join(dir, 'display-thumbs-reset-v1.flag') if (await fs().exists(marker)) return 0 const abs = await join(dir, IMG_DIR, 'thumbs') let entries = [] try { entries = await fs().readDir(abs) } catch (e) { entries = [] } let n = 0 for (const e of entries) { if (!e || e.isDirectory) continue if (!/_768\.(webp|jpg|jpeg)$/i.test(String(e.name))) continue try { await fs().remove(await join(abs, e.name)); n++ } catch (err) { /* 单个失败忽略 */ } } try { await fs().writeTextFile(marker, String(Date.now())) } catch (e) { /* 标记失败下次再试 */ } return n } catch (e) { return 0 } } // trash/ 轮转:超过 maxAgeDays 的文件直接删除(gcImages 只是移进来,不清) async function rotateTrash(maxAgeDays) { const days = Number(maxAgeDays) > 0 ? Number(maxAgeDays) : 30 try { if (!enabled() || !dir) return 0 const trashAbs = await join(dir, 'trash') const cutoff = Date.now() - days * 86400000 let removed = 0 const walk = async (abs, depth) => { if (depth > 3) return let entries = [] try { entries = await fs().readDir(abs) } catch (e) { return } for (const e of entries) { if (!e) continue const child = await join(abs, e.name) if (e.isDirectory) { await walk(child, depth + 1); continue } try { const st = await fs().stat(child) const mt = st && st.mtime ? new Date(st.mtime).getTime() : 0 if (mt && mt < cutoff) { await fs().remove(child); removed++ } } catch (err) { /* 单条失败忽略 */ } } } await walk(trashAbs, 0) return removed } catch (e) { return 0 } } // 图库缩略图:清单里只存 thumbHash,渲染时按需从 images/thumbs/ 读(避免 base64 撑爆 index.json) let thumbMapCache = null async function thumbFileMap() { if (thumbMapCache) return thumbMapCache const map = {} try { const abs = await join(dir, IMG_DIR, 'thumbs') const entries = await fs().readDir(abs) for (const e of entries) { if (!e || e.isDirectory) continue const base = String(e.name).replace(/\.[^.]+$/, '') if (!map[base]) map[base] = String(e.name) } } catch (e) { /* 没有 thumbs 目录就返回空表 */ } thumbMapCache = map return map } // v3.26.133:图库条目的**唯一**取图口径。 // 宫格要的只是 320 的小图,绝不该读 4K 原图(实测 150 次调用平均 11 秒、失败 83)。 // ① 有 thumbHash 且盘上有对应 jpg → objectURL // ② 否则按 assets 登记的相对路径,在**原生侧**生成 320 tier(按名字做稳定 hash,落在 thumbs/) async function galleryThumbOfEntry (f, max) { try { if (!enabled() || !dir || !f) return '' const m = Math.max(64, Number(max) || 320) if (f.thumbHash) { const u = await galleryThumbUrl(f.thumbHash) if (u) return u } const key = String(f.origIdb || f.idb || '') const a = key ? assets[key] : null if (!a || !a.f) return '' const abs = await join(dir, a.f) const h16 = await sha16(new TextEncoder().encode('gal:' + String(f.name || a.f))) const r = await makeDisplayThumbFromPath(h16, abs, m) return (r && r.url) || '' } catch (e) { return '' } } // v3.26.131:宫格缩略图改发 **objectURL**(同一张只读一次盘、只建一次 URL)。 // 原来每张都 base64 成 dataURL(20~40KB 字符串),164 张 ⇒ 每次开面板 3~6MB 字符串 + 164 次 IPC, // 这就是「能加载但很慢」的来源。objectURL 首帧即用,重复打开直接命中。 const galleryUrlCache = new Map() async function galleryThumbUrl(hash) { try { if (!enabled() || !dir || !hash) return '' const k = String(hash) const hit = galleryUrlCache.get(k) if (hit) { // 命中移到队尾(LRU) galleryUrlCache.delete(k); galleryUrlCache.set(k, hit) return hit } const map = await thumbFileMap() const name = map[k] if (!name) return '' const u8 = await fs().readFile(await join(dir, IMG_DIR, 'thumbs', name)) if (!u8 || !u8.length) return '' const mime = sniffMime(u8) || (/\.png$/i.test(name) ? 'image/png' : 'image/jpeg') const url = URL.createObjectURL(new Blob([u8], { type: mime })) galleryUrlCache.set(k, url) while (galleryUrlCache.size > 500) { const oldK = galleryUrlCache.keys().next().value try { URL.revokeObjectURL(galleryUrlCache.get(oldK)) } catch (e) { /* ignore */ } galleryUrlCache.delete(oldK) } return url } catch (e) { return '' } } async function galleryThumb(hash) { try { if (!enabled() || !dir || !hash) return '' const map = await thumbFileMap() const name = map[String(hash)] if (!name) return '' const u8 = await fs().readFile(await join(dir, IMG_DIR, 'thumbs', name)) if (!u8 || !u8.length) return '' const mime = /\.png$/i.test(name) ? 'image/png' : 'image/jpeg' return bytesToDataUrl(mime, u8) } catch (e) { return '' } } // 画布显示缩略图(768px)落盘:重启后直接命中,不用重新解码 4K 原图 // v3.25.78:缩略图可能是 webp(新)或 jpg(老),按扩展名决定 MIME。 // 旧代码把 WebP 字节写进 _768.jpg 名字里 ⇒ dataURL 声明成 image/jpeg,属于格式错配。 // v3.25.78:缩略图文件名曾把 WebP 写成 .jpg(老 bug),所以 MIME 必须按**魔数**判断, // 不能只看扩展名,否则 拿到错 MIME 的 blob 可能渲染成黑块。 function sniffMime (u8) { try { if (!u8 || u8.length < 12) return '' if (u8[0] === 0xFF && u8[1] === 0xD8 && u8[2] === 0xFF) return 'image/jpeg' if (u8[0] === 0x89 && u8[1] === 0x50 && u8[2] === 0x4E && u8[3] === 0x47) return 'image/png' if (u8[0] === 0x52 && u8[1] === 0x49 && u8[2] === 0x46 && u8[3] === 0x46 && u8[8] === 0x57 && u8[9] === 0x45 && u8[10] === 0x42 && u8[11] === 0x50) return 'image/webp' if (u8[0] === 0x47 && u8[1] === 0x49 && u8[2] === 0x46) return 'image/gif' } catch (e) { /* ignore */ } return '' } async function thumbFileOf (hash, max) { const base = await join(dir, IMG_DIR, 'thumbs', String(hash) + '_' + (Math.max(64, Number(max) || 768))) // v3.26.135:补 .png —— 原生 tier 对**带透明**的图输出 png,原来只查 webp/jpg, // 于是透明图的 tier 永远「查不到」⇒ 每次请求都重新生成(实测 1515 次调用就是这么来的)。 for (const ext of ['.webp', '.jpg', '.png']) { try { if (await fs().exists(base + ext)) { const mime = ext === '.webp' ? 'image/webp' : (ext === '.png' ? 'image/png' : 'image/jpeg'); return { path: base + ext, mime: mime } } } catch (e) { /* ignore */ } } return null } async function readDisplayThumb(hash, max) { try { if (!enabled() || !dir || !hash) return '' const f = await thumbFileOf(hash, max) if (!f) return '' const u8 = await fs().readFile(f.path) if (!u8 || !u8.length) return '' return bytesToDataUrl(sniffMime(u8) || f.mime, u8) } catch (e) { return '' } } // v3.25.73:缩略图以 Blob + objectURL 交给显示层(避免 dataURL 常驻 JS 堆) const thumbUrlCache = new Map() // hash → objectURL async function readDisplayThumbUrl(hash, max) { try { if (!enabled() || !dir || !hash) return '' const ck = String(hash) + '_' + (Math.max(64, Number(max) || 768)) const hit = thumbUrlCache.get(ck) if (hit) return hit const f = await thumbFileOf(hash, max) if (!f) return '' const u8 = await fs().readFile(f.path) if (!u8 || !u8.length) return '' const url = URL.createObjectURL(new Blob([u8], { type: sniffMime(u8) || f.mime })) thumbUrlCache.set(ck, url) // 不 revoke:这个 URL 可能正在被画布上的 使用,撤销会变成黑块/破图。 if (thumbUrlCache.size > 600) { const k = thumbUrlCache.keys().next().value; try { thumbUrlCache.delete(k) } catch (e) { /* ignore */ } } return url } catch (e) { return '' } } // v3.25.78:缩略图没有回收机制,历史上会无限增长(实测 470 个 / 67MB)。 // 这里按总大小封顶(默认 300MB,超了删最老的 20%),缩略图可再生,删掉不影响数据。 async function pruneThumbs (maxMB) { try { if (!enabled() || !dir) return 0 const cap = Math.max(50, Number(maxMB) || 300) * 1024 * 1024 const tdir = await join(dir, IMG_DIR, 'thumbs') if (!(await fs().exists(tdir))) return 0 const names = await fs().readDir(tdir) const files = [] let total = 0 for (const e of names) { const name = e && (e.name || e) if (!name || !/(_768\.(webp|jpg)|^[0-9a-f]{16}\.(webp|jpg|jpeg|png))$/i.test(String(name))) continue const abs = await join(tdir, String(name)) try { const st = await fs().stat(abs) const size = (st && st.size) || 0 total += size files.push({ abs, size, mtime: (st && st.mtime) ? new Date(st.mtime).getTime() : 0 }) } catch (err) { /* ignore */ } } if (total <= cap) return 0 files.sort((a, b) => a.mtime - b.mtime) const target = cap * 0.8 let removed = 0 for (const f of files) { if (total <= target) break try { await fs().remove(f.abs); total -= f.size; removed++ } catch (e) { /* ignore */ } } return removed } catch (e) { return 0 } } // v3.25.80:images/legacy 是旧版迁移残留。只删**未被任何画布/图库清单引用**且超过 7 天的文件, // 引用中的文件永远不动;返回删除数量。 async function cleanupLegacy (referencedNames) { try { if (!enabled() || !dir) return 0 const ldir = await join(dir, IMG_DIR, 'legacy') if (!(await fs().exists(ldir))) return 0 const keep = new Set((referencedNames || []).map((x) => String(x))) const names = await fs().readDir(ldir) const now = Date.now() let removed = 0 for (const e of names) { const name = e && (e.name || e) if (!name || keep.has(String(name))) continue const abs = await join(ldir, String(name)) try { const st = await fs().stat(abs) const mtime = (st && st.mtime) ? new Date(st.mtime).getTime() : 0 if (now - mtime < 7 * 86400e3) continue await fs().remove(abs) removed++ } catch (err) { /* ignore */ } } return removed } catch (e) { return 0 } } // v3.25.80:启动维护入口(缩略图封顶 + legacy 未引用清理),宿主只调这一个 async function maintain (opts) { const o = opts || {} const a = await pruneThumbs(o.maxMB).catch(() => 0) const b = await cleanupLegacy(o.keep).catch(() => 0) return { thumbs: a, legacy: b } } // v3.26.123:原生缩略图。有就返回,没有就让 Rust 按目标尺寸解码/缩放/编码后写盘,再读成 objectURL。 // 关键:整条链里 webview 只接触几十 KB 的小图,4K 原图永远不会被 WebKit 解码(mac 端 GB 级占用的根源)。 // 原生解码闸门(全局唯一收口):原图解码并发 ≤2,>4096px 的 ≤1。 // 所有插件/画布的缩略图都经这里 ⇒ 宿主第一次真正掌握"此刻有几张原图在被解码"。 const dec = { active: 0, big: 0, peak: 0, total: 0 } // 真正的闸门:并发上限 2;>1024px 的(走原图整幅解码)上限 1。 const runWithSlot = async (big, fn) => { const cap = () => (big ? 1 : 2) while (dec.active >= cap()) await new Promise((r) => setTimeout(r, 40)) dec.active++; dec.total++; if (big) dec.big++ if (dec.active > dec.peak) dec.peak = dec.active try { return await fn() } finally { dec.active--; if (big) dec.big-- } } function decodeStats () { return { active: dec.active, peak: dec.peak, total: dec.total, big: dec.big, queued: 0 } } // 按**绝对路径**生成 tier(相册的 {__file} 引用走这条) // v3.26.135:同一 (hash,max) 的生成**去重**。预热与宫格会同时要同一张, // 原来两边各跑一次 img_thumbs、同时写同一个文件 ⇒ 另一方可能读到写了一半的 jpg。 const thumbInflight = new Map() function makeDisplayThumbFromPath (hash, absPath, max) { const m = Math.max(64, Number(max) || 768) const key = String(hash) + '_' + m const hit = thumbInflight.get(key) if (hit) return hit const p = makeDisplayThumbFromPathInner(hash, absPath, m).finally(() => { thumbInflight.delete(key) }) thumbInflight.set(key, p) return p } async function makeDisplayThumbFromPathInner (hash, absPath, max) { try { if (!enabled() || !dir || !hash || !absPath) return null const m = max const have = await thumbFileOf(hash, m) if (have) { // 0 字节 = 上次并发写坏的截断文件:删掉重做,别把坏图缓存成 objectURL let size = 0 try { const st = await fs().stat(have.path); size = (st && st.size) || 0 } catch (e) { size = 0 } if (size > 0) return { url: await readDisplayThumbUrl(hash, m), path: have.path, cached: true } try { await fs().remove(have.path) } catch (e) { /* ignore */ } } const base = await join(dir, IMG_DIR, 'thumbs', String(hash) + '_' + m) try { await fs().mkdir(await join(dir, IMG_DIR, 'thumbs'), { recursive: true }) } catch (e) { /* ignore */ } const T = (typeof window !== 'undefined') ? window.__TAURI__ : null const inv = T && T.core && T.core.invoke if (typeof inv !== 'function') return null const r = await runWithSlot(m > 1024, () => inv('img_thumbs', { src: String(absPath), jobs: [{ base, max: m }] })) if (!r || !r.ok || !Array.isArray(r.files) || !r.files.length) return null const url = await readDisplayThumbUrl(hash, m) if (!url) return null return { url, path: r.files[0].path, w: r.files[0].w, h: r.files[0].h, bytes: r.files[0].bytes, cached: false } } catch (e) { return null } } // 把一段 dataURL 在**原生侧**缩到 max 长边(不经过 webview 解码)。 // 用途:插件拿到的是 dataURL(封面、节点图)时,也能避免 WebKit 整幅解码大图。 let tmpSeq = 0 async function resizeDataUrl (dataUrl, max) { try { if (!enabled() || !dir) return '' const s = String(dataUrl || '') const m = /^data:([^;,]+)?(;base64)?,(.*)$/.exec(s) if (!m || !m[2]) return '' const mime = String(m[1] || 'image/png').toLowerCase() const ext = mime.indexOf('jpeg') >= 0 ? 'jpg' : (mime.indexOf('webp') >= 0 ? 'webp' : (mime.indexOf('gif') >= 0 ? 'gif' : 'png')) const bin = atob(m[3]) const u8 = new Uint8Array(bin.length) for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i) const cfg = await join(dir, 'cache') try { await fs().mkdir(cfg, { recursive: true }) } catch (e) { /* ignore */ } tmpSeq = (tmpSeq + 1) % 100000 const tag = 'rt' + Date.now().toString(36) + tmpSeq const src = await join(cfg, tag + '.' + ext) const base = await join(cfg, tag + '_out') await fs().writeFile(src, u8) try { const t = (typeof window !== 'undefined') ? window.__TAURI__ : null const inv = t && t.core && t.core.invoke if (typeof inv !== 'function') return '' const r = await runWithSlot(true, () => inv('img_thumbs', { src, jobs: [{ base, max: Math.max(64, Number(max) || 512) }] })) if (!r || !r.ok || !Array.isArray(r.files) || !r.files.length) return '' const out = await fs().readFile(r.files[0].path) if (!out || !out.length) return '' const durl = bytesToDataUrl(sniffMime(out) || 'image/jpeg', out) try { await fs().remove(r.files[0].path) } catch (e) { /* ignore */ } return durl } finally { try { await fs().remove(src) } catch (e) { /* ignore */ } } } catch (e) { return '' } } async function makeDisplayThumb (hash, srcKey, max) { try { if (!enabled() || !dir || !hash || !srcKey) return null const a = assets[String(srcKey)] if (!a) return null const src = await join(dir, a.f) return await makeDisplayThumbFromPath(hash, src, max) } catch (e) { return null } } // v3.26.126:缩略图磁盘统计(诊断页用)。60s 缓存,避免每次开面板都 stat 400 个文件。 let thumbStatsCache = { at: 0, val: null } async function thumbStats () { try { if (!enabled() || !dir) return null const now = Date.now() if (thumbStatsCache.val && now - thumbStatsCache.at < 60000) return thumbStatsCache.val const tdir = await join(dir, IMG_DIR, 'thumbs') let list = [] try { list = await fs().readDir(tdir) } catch (e) { return null } let n = 0, bytes = 0, n512 = 0, n256 = 0, n768 = 0 for (const e of list) { if (!e || e.isDirectory) continue const name = String(e.name || '') n++ if (name.indexOf('_512') >= 0) n512++ else if (name.indexOf('_256') >= 0) n256++ else if (name.indexOf('_768') >= 0) n768++ try { const st = await fs().stat(await join(tdir, name)); bytes += (st && st.size) || 0 } catch (e) { /* ignore */ } } const val = { n: n, mb: Math.round((bytes / 1048576) * 10) / 10, n512: n512, n256: n256, n768: n768 } thumbStatsCache = { at: now, val: val } return val } catch (e) { return null } } async function writeDisplayThumbBlob(hash, blob) { try { if (!enabled() || !dir || !hash || !blob) return false const isWebp = String(blob.type || '').indexOf('webp') >= 0 const abs = await join(dir, IMG_DIR, 'thumbs', String(hash) + '_768' + (isWebp ? '.webp' : '.jpg')) if (await fs().exists(abs)) return true try { const other = await join(dir, IMG_DIR, 'thumbs', String(hash) + '_768' + (isWebp ? '.jpg' : '.webp')) if (await fs().exists(other)) return true } catch (e) { /* ignore */ } await fs().mkdir(await join(dir, IMG_DIR, 'thumbs'), { recursive: true }) const buf = new Uint8Array(await blob.arrayBuffer()) await fs().writeFile(abs, buf) return true } catch (e) { return false } } async function writeDisplayThumb(hash, dataUrl) { try { if (!enabled() || !dir || !hash || !dataUrl) return false const m = /^data:[^;]+;base64,(.*)$/.exec(String(dataUrl)) if (!m) return false const bin = atob(m[1]) const u8 = new Uint8Array(bin.length) for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i) const abs = await join(dir, IMG_DIR, 'thumbs', String(hash) + '_768.jpg') if (await fs().exists(abs)) return true await fs().mkdir(await join(dir, IMG_DIR, 'thumbs'), { recursive: true }) await fs().writeFile(abs, u8) return true } catch (e) { return false } } // 一次性:图库清单里历史遗留的 base64 data 删掉(缩略图已在 images/thumbs/) async function stripInlineGalleryThumbs() { try { const marker = await join(dir, 'gallery-data-stripped.flag') if (await fs().exists(marker)) return 0 const raw = mem['iwb_web_outputs'] if (!raw) { await fs().writeTextFile(marker, '0'); return 0 } const items = JSON.parse(raw) if (!Array.isArray(items)) return 0 const map = await thumbFileMap() let n = 0 for (const it of items) { if (!it || !it.data) continue if (it.thumbHash && map[String(it.thumbHash)]) { it.data = ''; n++ } } if (n) { mem['iwb_web_outputs'] = JSON.stringify(items); await flush() } await fs().writeTextFile(marker, String(n)) return n } catch (e) { return 0 } } async function gcImages(opts) { const dryRun = !!(opts && opts.dryRun) try { if (!enabled() || !dir) return { ok: false, error: '资料目录未就绪' } const used = new Set(Object.keys(assets).map((k) => assets[k] && assets[k].f).filter(Boolean)) /* v3.25.8:assets 登记表是唯一的「在用」判据,但它可能因为恢复备份/迁移而落后于画布。 * 只看 assets 会把画布仍在引用的图片当孤儿挪进 trash/ —— 节点随即变成占位图, * 而且用户重新拖入时又被同图去重挡回来(那条链路已废)。 * 这里把 canvases/*.json 里出现的 {__blob} key 也算作在用:宁可留下几 MB,也不误删用户图片。 */ const canvasKeys = new Set() try { const cd = await join(dir, 'canvases') const list = await fs().readDir(cd) for (const e of list) { if (!e || e.isDirectory || !/\.json$/i.test(e.name) || e.name === 'active.json') continue let txt = '' try { txt = await fs().readTextFile(await join(cd, e.name)) } catch (err) { continue } const m = txt.match(/"__blob"\s*:\s*"([^"]+)"/g) || [] for (const hit of m) { const km = /"([^"]+)"$/.exec(hit) if (km) canvasKeys.add(km[1]) } } } catch (e) { /* 画布读不到就退回旧判据 */ } const referenced = new Set() for (const k of canvasKeys) { const a = assets[k]; if (a && a.f) referenced.add(a.f) } referenced.forEach((f) => used.add(f)) const imgAbs = await join(dir, IMG_DIR) // 子目录也要扫:images/{canvas,gallery,thumbs,legacy}/ 里的孤儿同样占空间 const subs = ['', 'canvas', 'gallery', 'thumbs', 'legacy'] const orphans = [] for (const sub of subs) { const abs = sub ? await join(imgAbs, sub) : imgAbs let entries = [] try { entries = await fs().readDir(abs) } catch (e) { continue } for (const e of entries) { if (!e || e.isDirectory) continue const rel = IMG_DIR + '/' + (sub ? sub + '/' : '') + e.name if (!used.has(rel)) orphans.push({ sub: sub, name: e.name, rel: rel }) } } // 断链:画布引用了、但登记表里没有的 key —— 这类节点的图**已经显示不出来**, // GC 不会动它们(文件根本不在),但值得在确认弹窗里报数,让用户知道数据已经缺了。 const dangling = Array.from(canvasKeys).filter((k) => !assets[k]).length const keptByCanvas = referenced.size if (dryRun || !orphans.length) return { ok: true, orphans: orphans.length, moved: 0, dryRun: dryRun, dangling: dangling, keptByCanvas: keptByCanvas } const trashAbs = await join(dir, 'trash') let moved = 0 for (const item of orphans) { try { const targetDir = item.sub ? await join(trashAbs, item.sub) : trashAbs await fs().mkdir(targetDir, { recursive: true }) await fs().rename(await join(imgAbs, item.sub, item.name), await join(targetDir, item.name)) moved++ } catch (e) { /* 单条失败忽略 */ } } return { ok: true, orphans: orphans.length, moved: moved, dryRun: dryRun, dangling: dangling, keptByCanvas: keptByCanvas } } catch (e) { return { ok: false, error: String((e && e.message) || e) } } } /* 删除指定 key 的图片字节(2026-11-24):图库删图时索引清了、文件却还在 images/gallery/ 里, * 用户看到的「数据库里没删」就是这个。这里按登记表把文件移进 trash/(不直删,可找回), * 同时删掉登记项;画布仍引用同一文件时不搬(同一图可能既被画布引用又被图库引用)。 */ async function deleteImageBytes(keys) { try { if (!enabled() || !dir) return { ok: false, error: '资料目录未就绪' } const list = Array.isArray(keys) ? keys : [] if (!list.length) return { ok: true, moved: 0 } const canvasKeys = new Set() try { const cd = await join(dir, 'canvases') const ents = await fs().readDir(cd) for (const e of ents) { if (!e || e.isDirectory || !/\.json$/i.test(e.name) || e.name === 'active.json') continue let txt = '' try { txt = await fs().readTextFile(await join(cd, e.name)) } catch (err) { continue } for (const hit of (txt.match(/"__blob"\s*:\s*"([^"]+)"/g) || [])) { const km = /"([^"]+)"$/.exec(hit); if (km) canvasKeys.add(km[1]) } } } catch (e) { /* 画布读不到:按「不引用」处理,仍移到 trash 而非直删 */ } const keepFiles = new Set() for (const k of canvasKeys) { const a = assets[k]; if (a && a.f) keepFiles.add(a.f) } const trashAbs = await join(dir, 'trash') let moved = 0 for (const key of list) { const k = String(key) const a = assets[k] if (a && a.f) { delete assets[k] if (!keepFiles.has(a.f)) { try { const sub = String(a.f).split('/')[1] || '' const targetDir = sub ? await join(trashAbs, sub) : trashAbs await fs().mkdir(targetDir, { recursive: true }) await fs().rename(await join(dir, a.f), await join(targetDir, a.f.split('/').pop())) moved++ } catch (e) { /* 单条失败忽略 */ } } } if (Object.prototype.hasOwnProperty.call(small, k)) delete small[k] } schedule() return { ok: true, moved: moved } } catch (e) { return { ok: false, error: String((e && e.message) || e) } } } // 图库落盘自检(2026-11-26):只读。按索引条目查 assets 登记 + 磁盘文件是否真的存在, // 并顺带列出 images/gallery 里没被任何条目引用的文件(删图只清索引时的孤儿)。 // 只做 exists,不读字节 —— 几百张原图读回 base64 会把堆顶撑高(诊断页点一下不该更卡)。 async function galleryAudit (index) { if (!enabled() || !dir) return { ok: false, error: '资料目录未就绪(浏览器环境)' } const list = Array.isArray(index) ? index : [] const rows = new Array(list.length) let cursor = 0 const existsAt = async (rel) => { if (!rel) return false try { return !!(await fs().exists(await join(dir, rel))) } catch (e) { return false } } const worker = async () => { while (true) { const i = cursor++ if (i >= list.length) return const it = list[i] || {} const name = String(it.name || '') const origKey = String(it.origIdb || ('out_orig_' + name)) const thumbKey = String(it.idb || ('out_' + name)) const oa = assets[origKey] const ta = assets[thumbKey] const origPath = (oa && oa.f) || '' const thumbPath = (ta && ta.f) || '' rows[i] = { name, origKey: !!oa, thumbKey: !!ta, origPath, thumbPath, orig: await existsAt(origPath), thumb: await existsAt(thumbPath), } } } // 并发 4:几十条是常态,串行会让诊断页点一下等好几秒;再高会把 IPC 打满。 await Promise.all([worker(), worker(), worker(), worker()]) let galleryFiles = [] try { const ents = await fs().readDir(await join(dir, IMG_DIR, IMG_CAT.gallery)) galleryFiles = (ents || []).filter((e) => e && !e.isDirectory).map((e) => String(e.name || '')).filter(Boolean) } catch (e) { galleryFiles = [] } return { ok: true, dir: dir, rows: rows, galleryFiles: galleryFiles } } // 2026-11-24:按图库条目名删字节 —— app.js 只传 names + 索引,逻辑留在这里(app.js 行数棘轮)。 async function deleteGalleryBytesFor (names, index) { const wanted = Array.isArray(names) ? names : [] if (!wanted.length) return { ok: true, moved: 0 } const keys = [] for (const it of (Array.isArray(index) ? index : [])) { if (!it || wanted.indexOf(it.name) < 0) continue if (it.idb) keys.push(it.idb) if (it.origIdb) keys.push(it.origIdb) } return deleteImageBytes(keys) } global.IWBStorageFile = { enabled, ready: init, flush, // 供其它模块把诊断写进 _boot.log(v3.26.109) logLine: (m) => blog(m), runtime, pickDir, switchTo, migrateTo, deleteImageBytes, deleteGalleryBytesFor, galleryAudit, gcImages, rotateTrash, galleryThumb, galleryThumbUrl, galleryThumbOfEntry, readDisplayThumb, readDisplayThumbUrl, makeDisplayThumb, makeDisplayThumbFromPath, resizeDataUrl, decodeStats, thumbStats, writeDisplayThumb, writeDisplayThumbBlob, pruneThumbs, cleanupLegacy, maintain, plugins: { manifest: pluginManifest, read: pluginRead, write: pluginWrite, remove: pluginRemove, dir: pluginDir, listLocal: pluginListLocal, listDirs: pluginListDirs, readFile: pluginReadFile, writeFile: pluginWriteFile, writeBinary: pluginWriteBinary, mkdir: pluginMkdir, removeDir: pluginRemoveDir, renameDir: pluginRenameDir, existsDir: pluginExistsDir }, pluginData: { read: pluginDataRead, write: pluginDataWrite, remove: pluginDataRemove, list: pluginDataList }, pluginFiles: { put: pluginFilePut, get: pluginFileGet, list: pluginFileList, remove: pluginFileRemove, stat: pluginFileStat, dir: pluginFilesDir, readBytes: pluginFileReadBytes, listAll: pluginFilesListAll }, storage: () => storage, kv: () => kv, dir: () => dir, setDir: async (next) => { dir = String(next || ''); await flush();}, stats: () => ({ dir, keys: Object.keys(mem).length, images: Object.keys(assets).length }), __internals: { snapshot, loadInto, sha16, extOf, dataUrlToBytes, bytesToDataUrl, pluginFileNameOk }, } // 关窗/收托盘前强制刷盘(beforeunload 在桌面端不保证,但能救一次是一次) // 落盘兜底:桌面端点关闭是「收进托盘」,beforeunload 不一定触发; // 窗口被隐藏/失焦时也刷一次,避免最后 800ms 的改动只存在内存里。 try { global.addEventListener('beforeunload', () => { try { flush() } catch (e) { /* ignore */ } }) global.addEventListener('pagehide', () => { try { flush() } catch (e) { /* ignore */ } }) if (global.document && global.document.addEventListener) { global.document.addEventListener('visibilitychange', () => { try { if (global.document.visibilityState === 'hidden') flush() } catch (e) { /* ignore */ } }) } if (global.addEventListener) global.addEventListener('blur', () => { try { flush() } catch (e) { /* ignore */ } }) } catch (e) { /* ignore */ } })(typeof window !== 'undefined' ? window : globalThis)