;(function (global) { 'use strict' // 失败留痕(2026-11-10):写路径失败不再纯静默 —— 统一走 IWBMetricsSwallow // (src/runtime-metrics.js 导出:计数 + 面包屑,诊断页可见)。环境无此全局时安全退化。 const _swallow = (area, e) => { try { const f = global.IWBMetricsSwallow; if (typeof f === 'function') f(area, e) } catch (_) { /* ignore */ } } const result = global.IWBStorageResult const unwrap = (value) => value && value.ok === true && Object.prototype.hasOwnProperty.call(value, 'value') ? value.value : value const create = (options) => { const config = options || {} const local = config.local const indexed = config.indexedDb const key = config.key || 'iwb_web_outputs' const prefix = config.prefix || 'out_' const limit = Number(config.limit) > 0 ? Number(config.limit) : 10000 const hydrate = config.hydrate // 跨标签串行化:图库索引是 localStorage 的「读-改-写」,两个标签并发会互相覆盖丢失条目。 // 用 Web Locks 串行化 add/remove/clear;浏览器不支持时退回直连(行为同旧版)。 const locksApi = () => (global.navigator && global.navigator.locks && typeof global.navigator.locks.request === 'function') ? global.navigator.locks : null const withLock = (fn) => { const l = locksApi(); return l ? l.request('iwb_outputs_rw', fn) : fn() } const readIndex = () => { const value = local.get(key, []) if (value && value.ok === false) return value return result.ok(Array.isArray(unwrap(value)) ? unwrap(value) : []) } const doAdd = async (items, options) => { const indexResult = readIndex() if (!indexResult.ok) return indexResult const index = indexResult.value const added = [] for (const item of items || []) if (item && item.url) { const name = item.name || ('gen_' + Date.now() + '_' + Math.floor(Math.random() * 1e6) + '.png') index.push({ name, url: item.url, size: item.size || 0, mtime: item.mtime || Date.now(), w: item.width || item.w || 0, h: item.height || item.h || 0, label: item.label || '' }) added.push(name) } const opts = options || {} const ret = opts.retention || {} const now = Number(opts.now) || Date.now() let kept = index.slice() if (Number(ret.maxDays) > 0) kept = kept.filter((item) => now - Number(item.mtime || 0) <= Number(ret.maxDays) * 86400e3) kept.sort((a, b) => Number(a.mtime || 0) - Number(b.mtime || 0)) if (Number(ret.maxFiles) > 0) kept = kept.slice(-Number(ret.maxFiles)) const keepNames = new Set(kept.map((item) => item.name)) const removed = index.filter((item) => !keepNames.has(item.name)) const stored = local.set(key, kept) if (stored && stored.ok === false) return stored // 回收旧图时单个 IDB 删除失败不应让整次写入抛错(索引已落盘,孤儿 blob 无害)—— 但必须留痕 if (indexed && typeof indexed.del === 'function') for (const item of removed) if (item && item.idb) { try { await indexed.del(item.idb) } catch (e) { _swallow('save', e) } } return result.ok(added.filter((name) => keepNames.has(name)), { removed: removed.length }) } const doRemove = async (names) => { const indexResult = readIndex() if (!indexResult.ok) return indexResult const wanted = Array.isArray(names) ? names : [] const removed = indexResult.value.filter((item) => wanted.indexOf(item.name) >= 0) const stored = local.set(key, indexResult.value.filter((item) => wanted.indexOf(item.name) < 0)) if (stored && stored.ok === false) return stored // 回收旧图时单个 IDB 删除失败不应让整次写入抛错(索引已落盘,孤儿 blob 无害)—— 但必须留痕 if (indexed && typeof indexed.del === 'function') for (const item of removed) if (item && item.idb) { try { await indexed.del(item.idb) } catch (e) { _swallow('save', e) } } return result.ok(true, { removed: removed.length }) } const doClear = async () => { const indexResult = readIndex() if (!indexResult.ok) return indexResult // 顺序:**先清索引、再删字节**。索引是 UI 的唯一真相;若先删字节后索引写失败, // 会留下指向已删字节的悬空索引(列表里永远打不开的坏图)。反过来:索引已清, // 即使删字节失败也只留孤儿 blob(占空间、可回收),不会破坏 UI。 const stored = local.set(key, []) if (stored && stored.ok === false) return stored if (indexed && typeof indexed.keys === 'function' && typeof indexed.del === 'function') { // indexed.keys() 失败时返回的是失败对象(truthy 且不可迭代),直接 for…of 会抛异常。 // 只接受成功结果里的数组;IDB 清理按 best-effort 处理(失败只留孤儿 blob)。 const listed = await indexed.keys() const keys = listed && listed.ok === true && Array.isArray(listed.value) ? listed.value : [] for (const item of keys) if (String(item).indexOf(prefix) === 0) { try { await indexed.del(item) } catch (e) { _swallow('save', e) } } } return result.ok(true) } // 通用「读-改-写」(2026-11-16):把调用方自己的变更函数放进同一把 iwb_outputs_rw 锁里执行。 // 为什么需要它:add / remove / clear 之外,app.js 还有几条**自己读索引、改完写回**的路径 // (标记 folderStatus 缺失、缩略图落 IDB 后回写 idb 键、备份导入整表、清理原图后删 origIdb)。 // 它们此前直连 localStorage 的 OUT_KEY,绕过了本模块的锁 —— 两个标签页各自的「读-改-写」 // 在浏览器里是两个渲染进程并行,可以真实交错(A 读 [x] / B 读 [x] / A 写 [x,新1] / B 写 [x,新2] // ⇒ 新1 消失)。用户侧表现就是「图库莫名少条目」,且无法重置复现。 // 契约:fn(currentIndex) 收到索引副本,返回**新数组**即写入;返回 null / undefined 表示放弃写入。 // 回调必须是纯计算(不要在里面 await 别的东西)—— 持锁期间做 IO 会拖慢另一个标签页的归档。 const doMutate = async (fn) => { const indexResult = readIndex() if (!indexResult.ok) return indexResult let next try { next = fn(indexResult.value.slice()) } catch (e) { return result.fail(result.from(e, 'unknown')) } if (next === null || next === undefined) return result.ok(false, { changed: false }) if (!Array.isArray(next)) return result.fail(result.error('validation', 'mutate-must-return-array', 'mutate 必须返回数组或 null', false)) const stored = local.set(key, next) if (stored && stored.ok === false) return stored return result.ok(true, { changed: true, count: next.length }) } return { async list(options) { try { const indexResult = readIndex() if (!indexResult.ok) return indexResult const opts = options || {} const ret = opts.retention || {} const now = Number(opts.now) || Date.now() let files = indexResult.value.slice() if (Number(ret.maxDays) > 0) files = files.filter((item) => now - Number(item.mtime || 0) <= Number(ret.maxDays) * 86400e3) files.sort((a, b) => Number(b.mtime || 0) - Number(a.mtime || 0)) files = files.slice(0, Number(ret.maxFiles) > 0 ? Number(ret.maxFiles) : limit) const count = Number(opts.limit) const targets = count > 0 ? files.slice(0, count) : files // v3.87.37:metaOnly=true 时**只返回元数据**(不把每条的数据读回内存)。 // 之前每次生成归档都会 hydrate 整库(实测库里有 109 条),是大内存尖峰的来源。 if (opts.metaOnly === true) return result.ok({ files, retention: ret, metaOnly: true }) if (hydrate && typeof hydrate === 'function') { const hydrated = await hydrate(targets) if (hydrated && Array.isArray(hydrated.items)) for (let i = 0; i < targets.length; i++) if (hydrated.items[i] && hydrated.items[i].data !== undefined) targets[i].data = hydrated.items[i].data } else if (indexed && typeof indexed.get === 'function') { await Promise.all(targets.map(async (item) => { if (item && item.idb) { const value = unwrap(await indexed.get(item.idb)); if (value) item.data = value } })) } return result.ok({ files, retention: ret }) } catch (e) { return result.fail(result.from(e, 'unavailable'), { degraded: true }) } }, add(items, options) { return withLock(() => doAdd(items, options)) }, remove(names) { return withLock(() => doRemove(names)) }, clear() { return withLock(() => doClear()) }, mutate(fn) { return withLock(() => doMutate(fn)) }, } } global.IWBStorageOutputs = { create } })(typeof window !== 'undefined' ? window : globalThis)