136 lines
6.5 KiB
JavaScript
136 lines
6.5 KiB
JavaScript
/* 本地自动备份(2026-11-07)
|
||
*
|
||
* 目的:把 localStorage 里所有 `iwb_*` 键做**每日一次**的快照,存进 IndexedDB 的 `kv` store,
|
||
* 保留最近 N 份,并提供一键还原。
|
||
*
|
||
* 能防什么(说清楚,避免误解):
|
||
* ✅ 误删画板 / 单个键被写坏 / 保存逻辑回归导致数据被覆盖 —— 可从最近快照还原
|
||
* ✅ 迁移/清理逻辑出错 —— 有可回退的副本
|
||
* ❌ **不能**防「浏览器清空整个站点数据」(用户清站点数据、隐私模式退出、系统清理会把
|
||
* localStorage 与 IndexedDB 一起清掉)—— 那只能靠「导出成文件」保存到磁盘。
|
||
*
|
||
* 设计取舍:
|
||
* - 只备份 localStorage 的 `iwb_*` 键(画布结构/设置/提示词库缓存);**不含图片二进制**
|
||
* (图片在 IndexedDB `images`,体积大且可重新获取)
|
||
* - 快照是**原样字符串的字典**,还原 = 逐键写回,不经过任何序列化/校验逻辑(避免二次损坏)
|
||
* - 自动触发:距上次备份 ≥ 24h 且页面空闲时(不阻塞交互)
|
||
*/
|
||
;(function (global) {
|
||
'use strict'
|
||
const PREFIX = 'autobackup:'
|
||
const MAX_KEEP = 7
|
||
// 单份快照体积护栏(2026-11-07):localStorage 本身被浏览器限制在 ~5-10MB,
|
||
// 快照显著超过这个量级只可能是异常(键失控增长/误写入大对象)。
|
||
// 跳过并留原因,而不是把异常数据复制 7 份进 IndexedDB。
|
||
const MAX_SNAPSHOT_BYTES = 16 * 1024 * 1024
|
||
const MIN_INTERVAL_MS = 24 * 60 * 60 * 1000
|
||
|
||
function create (options) {
|
||
const opt = options || {}
|
||
const getStore = opt.getStore || (() => {
|
||
try {
|
||
const sl = global.IWBStorageLocal
|
||
return sl && typeof sl.getStore === 'function' ? sl.getStore() : null
|
||
} catch (e) { return null }
|
||
})
|
||
const getIdb = opt.getIdb || (() => {
|
||
try {
|
||
const f = global.IWBStorageIndexedDB
|
||
if (!f || typeof f.create !== 'function') return null
|
||
const contract = (global.IWBStorageContract && global.IWBStorageContract.indexedDb) || undefined
|
||
return f.create({ contract: contract })
|
||
} catch (e) { return null }
|
||
})
|
||
const nowFn = opt.now || (() => Date.now())
|
||
|
||
// 收集所有 iwb_* 键的**原始字符串值**(不 JSON.parse,避免二次序列化差异)
|
||
function collect () {
|
||
const st = getStore()
|
||
if (!st) return null
|
||
const keys = {}
|
||
for (const k of st.keys()) {
|
||
if (!k || k.indexOf('iwb_') !== 0) continue
|
||
if (k.indexOf('iwb_ws_bak_') === 0) continue // 已有的备份键不再套娃
|
||
if (k === 'iwb_web_workspaces_legacy') continue // 历史遗留整份副本,体积大且是重复数据
|
||
try { const v = st.rawGet(k, null); if (v !== null && v !== undefined) keys[k] = v } catch (e) { /* 单键读失败不影响其余 */ }
|
||
}
|
||
return keys
|
||
}
|
||
|
||
function bytesOf (obj) {
|
||
try { return JSON.stringify(obj).length } catch (e) { return 0 }
|
||
}
|
||
|
||
async function list () {
|
||
const idb = getIdb()
|
||
if (!idb || typeof idb.kvGet !== 'function') return []
|
||
// kv store 没有 keys(prefix) 接口 → 用约定键 + 索引键两种方式兼容:这里维护一个索引键
|
||
const idx = await idb.kvGet(PREFIX + 'index').catch(() => null)
|
||
const arr = (idx && idx.ok && Array.isArray(idx.value)) ? idx.value : []
|
||
const out = []
|
||
for (const name of arr) {
|
||
const r = await idb.kvGet(PREFIX + name).catch(() => null)
|
||
const snap = (r && r.ok) ? r.value : null
|
||
if (snap) out.push({ name: name, at: snap.at || 0, keyCount: Object.keys(snap.keys || {}).length, bytes: snap.bytes || 0 })
|
||
}
|
||
return out.sort((a, b) => b.at - a.at)
|
||
}
|
||
|
||
async function save (reason) {
|
||
const idb = getIdb()
|
||
if (!idb || typeof idb.kvPut !== 'function') return { ok: false, error: 'indexedDB 不可用' }
|
||
const keys = collect()
|
||
if (!keys) return { ok: false, error: 'localStorage 不可用' }
|
||
const at = nowFn()
|
||
const snap = { at: at, reason: reason || 'auto', version: opt.version || '', keys: keys }
|
||
snap.bytes = bytesOf(snap.keys)
|
||
if (snap.bytes > MAX_SNAPSHOT_BYTES) {
|
||
return { ok: false, error: '快照 ' + Math.round(snap.bytes / 1048576) + 'MB 超过护栏 ' + Math.round(MAX_SNAPSHOT_BYTES / 1048576) + 'MB(疑似异常数据),本次跳过' }
|
||
}
|
||
// 键名用 ISO 时间,天然按名排序 = 按时间排序
|
||
const name = new Date(at).toISOString().replace(/[:.]/g, '-')
|
||
const put = await idb.kvPut(PREFIX + name, snap).catch(() => null)
|
||
if (!put || !put.ok) return { ok: false, error: '写入备份失败' }
|
||
// 更新索引 + 裁剪
|
||
const idxR = await idb.kvGet(PREFIX + 'index').catch(() => null)
|
||
const arr = ((idxR && idxR.ok && Array.isArray(idxR.value)) ? idxR.value : []).concat([name])
|
||
const keep = arr.slice(-MAX_KEEP)
|
||
const drop = arr.slice(0, Math.max(0, arr.length - MAX_KEEP))
|
||
for (const d of drop) { try { await idb.kvDel(PREFIX + d) } catch (e) { /* ignore */ } }
|
||
await idb.kvPut(PREFIX + 'index', keep).catch(() => null)
|
||
return { ok: true, name: name, at: at, keyCount: Object.keys(keys).length, bytes: snap.bytes }
|
||
}
|
||
|
||
// 距上次自动备份是否已超过间隔
|
||
async function due () {
|
||
const all = await list()
|
||
if (!all.length) return true
|
||
return (nowFn() - all[0].at) >= MIN_INTERVAL_MS
|
||
}
|
||
|
||
async function read (name) {
|
||
const idb = getIdb()
|
||
if (!idb || typeof idb.kvGet !== 'function') return null
|
||
const r = await idb.kvGet(PREFIX + name).catch(() => null)
|
||
return (r && r.ok) ? r.value : null
|
||
}
|
||
|
||
// 还原:把快照里的键逐条写回(只写快照中存在的键,不删除当前多出来的键)
|
||
async function restore (name) {
|
||
const snap = await read(name)
|
||
if (!snap || !snap.keys) return { ok: false, error: '备份不存在或已损坏' }
|
||
const st = getStore()
|
||
if (!st) return { ok: false, error: 'localStorage 不可用' }
|
||
let written = 0, failed = 0
|
||
for (const k of Object.keys(snap.keys)) {
|
||
try { if (st.rawSet(k, snap.keys[k])) written += 1; else failed += 1 } catch (e) { failed += 1 }
|
||
}
|
||
return { ok: failed === 0, written: written, failed: failed, at: snap.at }
|
||
}
|
||
|
||
return { collect, list, save, due, read, restore, MAX_KEEP, MIN_INTERVAL_MS, MAX_SNAPSHOT_BYTES }
|
||
}
|
||
|
||
global.IWBStorageAutoBackup = { create }
|
||
})(typeof window !== 'undefined' ? window : globalThis)
|