refactor(app): 插件加载/市场/备份抽成 src 模块(app.js 8880→8764 行);备份包含插件
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m31s

This commit is contained in:
qiqi committed 2026-11-17 15:14:46 +08:00
1 parent 0ec11bfca8
commit ce575d2640
11 files changed
+297 -149

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
/* runtime-plugin-backup.js —— 插件进出备份
*
* 备份里带上插件清单与源码(体积很小),换机器恢复后不必重装。
* collect() → [{ id, version, file, integrity, code }]
* restore(v) → 写回 <资料目录>/plugins/ 并合并清单(备份里没有的插件保留)
*/
;(function (global) {
'use strict'
function store () {
const F = global.IWBStorageFile || null
return (F && F.plugins) ? F.plugins : null
}
async function collect () {
const s = store()
if (!s) return []
let list = []
try { list = await s.manifest() } catch (e) { return [] }
const out = []
for (const e of (Array.isArray(list) ? list : [])) {
if (!e || !e.id || !e.file) continue
try {
const text = await s.read(e.file)
out.push({ id: e.id, version: e.version || '', file: e.file, integrity: e.integrity || '', code: String(text || '') })
} catch (err) { /* 单个插件读失败不影响其它 */ }
}
return out
}
async function restore (list) {
const s = store()
if (!s || !Array.isArray(list) || !list.length) return 0
let cur = []
try { cur = await s.manifest() } catch (e) { cur = [] }
const byId = new Map((Array.isArray(cur) ? cur : []).map(function (e) { return [String(e && e.id), e] }))
let n = 0
for (const p of list) {
if (!p || !p.id || !p.file) continue
if (!/^[A-Za-z0-9._-]+$/.test(String(p.file))) continue
try {
await s.write(String(p.file), String(p.code || ''))
byId.set(String(p.id), { id: String(p.id), file: String(p.file), version: String(p.version || ''), integrity: String(p.integrity || '') })
n++
} catch (err) { /* 单个失败忽略 */ }
}
try { await s.write('index.json', JSON.stringify(Array.from(byId.values()))) } catch (e) { /* ignore */ }
return n
}
global.IWBRuntimePluginBackup = { collect: collect, restore: restore }
})(typeof window !== 'undefined' ? window : globalThis)
+120
View File
@@ -0,0 +1,120 @@
/* runtime-plugin-loader.js —— 插件脚本加载(内置 / 外部 / 本地开发)
*
* 从 app.js 抽出来:app.js 只做装配,加载细节在这里。
* 三个入口都返回 boolean,并把状态写回传进来的 record(status/error),供插件面板展示。
* · loadBuiltin :同源 /plugins/<file>,走 SRI(integrity 强制校验)
* · loadExternal :<资料目录>/plugins/<file>,先读文本 → WebCrypto 校验 sha256 → blob 注入
* · loadLocal :开发者模式,code 已在内存里(免签名),blob 注入
*/
;(function (global) {
'use strict'
function host () {
return global.IWBPluginHost || null
}
// 外部插件源(<资料目录>/plugins/ 的读写封装)
function source () {
const F = global.IWBStorageFile || null
return (F && F.plugins && typeof F.plugins.read === 'function') ? F.plugins : null
}
async function verifyCode (code, integrity) {
if (!integrity) return false
const expect = String(integrity).replace(/^sha256-/, '')
const buf = await global.crypto.subtle.digest('SHA-256', new global.TextEncoder().encode(code))
const u8 = new Uint8Array(buf)
let bin = ''
for (let i = 0; i < u8.length; i++) bin += String.fromCharCode(u8[i])
return global.btoa(bin) === expect
}
// 注入一段脚本并等它执行完(插件在加载期自我注册)
function inject (attrs) {
return new Promise(function (resolve, reject) {
const script = global.document.createElement('script')
script.src = attrs.src
script.async = false
if (attrs.integrity) { script.integrity = attrs.integrity; script.crossOrigin = 'anonymous' }
script.onload = function () { resolve() }
script.onerror = function () { reject(new Error(attrs.error || '脚本加载失败')) }
global.document.head.appendChild(script)
})
}
function markResult (record) {
const H = host()
const registered = !!(H && typeof H.list === 'function' && H.list().some(function (p) { return p.id === record.id }))
record.status = registered ? 'loaded' : 'not-registered'
if (registered && typeof H.isEnabled === 'function' && H.isEnabled(record.id)) H.setEnabled(record.id, true)
return record.status === 'loaded'
}
async function loadBuiltin (record) {
record.status = 'loading'
const integrity = record.integrity
try {
await inject({
src: '/plugins/' + record.file,
integrity: integrity,
error: integrity ? '脚本完整性校验失败(integrity 不符或加载失败)' : '脚本加载失败'
})
return markResult(record)
} catch (err) {
record.status = 'error'
record.error = String((err && err.message) || err)
return false
}
}
async function loadExternal (record) {
record.status = 'loading'
const src = source()
if (!src) { record.status = 'error'; record.error = '外部插件不可用'; return false }
try {
const code = await src.read(record.file)
if (record.integrity) {
const ok = await verifyCode(code, record.integrity)
if (!ok) throw new Error('完整性校验失败(外部插件)')
}
const url = global.URL.createObjectURL(new global.Blob([code], { type: 'text/javascript' }))
try {
await inject({ src: url, error: '外部插件脚本执行失败' })
} finally {
setTimeout(function () { try { global.URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 30000)
}
return markResult(record)
} catch (err) {
record.status = 'error'
record.error = String((err && err.message) || err)
return false
}
}
async function loadLocal (record) {
record.status = 'loading'
try {
const code = String(record.code || '')
if (!code) throw new Error('插件源码为空')
const url = global.URL.createObjectURL(new global.Blob([code], { type: 'text/javascript' }))
try {
await inject({ src: url, error: '本地插件脚本执行失败' })
} finally {
setTimeout(function () { try { global.URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 30000)
}
return markResult(record)
} catch (err) {
record.status = 'error'
record.error = String((err && err.message) || err)
return false
}
}
global.IWBRuntimePluginLoader = {
source: source,
verifyCode: verifyCode,
loadBuiltin: loadBuiltin,
loadExternal: loadExternal,
loadLocal: loadLocal
}
})(typeof window !== 'undefined' ? window : globalThis)
+73
View File
@@ -0,0 +1,73 @@
/* runtime-plugin-market.js —— 插件市场(下载 / 校验 / 安装 / 卸载)
*
* 索引:https://market.maqiart.eu.org/index.json,产物同域 plugin-<id>.<hash>.js
* 落点:<资料目录>/plugins/(清单 index.json + 插件文件)
* 校验:市场索引里的 sha256(hex)与下载文本比对,不符直接拒绝
*/
;(function (global) {
'use strict'
const MARKET_URL = 'https://market.maqiart.eu.org/index.json'
function store () {
const F = global.IWBStorageFile || null
return (F && F.plugins) ? F.plugins : null
}
// 桌面端优先走 Tauri 原生 HTTP(WKWebView 在代理/fake-IP 环境下 fetch 会 Load failed)
function marketFetch (url) {
const T = (global.__TAURI__ && global.__TAURI__.http) ? global.__TAURI__.http : null
if (T && typeof T.fetch === 'function') return T.fetch(url)
return global.fetch(url, { cache: 'no-store' })
}
async function list () {
const resp = await marketFetch(MARKET_URL)
if (!resp.ok) throw new Error('市场不可达:HTTP ' + resp.status)
const j = await resp.json()
return Array.isArray(j && j.plugins) ? j.plugins : []
}
async function installed () {
const s = store()
if (!s) return []
return await s.manifest()
}
async function install (id) {
try {
const items = await list()
const item = items.find(function (p) { return p && p.id === id })
if (!item) return { ok: false, error: '市场里没有这个插件' }
const base = MARKET_URL.replace(/index\.json$/, '')
const resp = await marketFetch(base + item.file)
if (!resp.ok) throw new Error('下载失败:HTTP ' + resp.status)
const text = await resp.text()
const buf = await global.crypto.subtle.digest('SHA-256', new global.TextEncoder().encode(text))
const hex = Array.from(new Uint8Array(buf)).map(function (b) { return b.toString(16).padStart(2, '0') }).join('')
if (item.sha256 && hex !== item.sha256) return { ok: false, error: '校验失败(sha256 不符)' }
const s = store()
if (!s) return { ok: false, error: '外部插件目录不可用' }
const file = String(item.file).split('/').pop()
await s.write(file, text)
const cur = await s.manifest()
const next = cur.filter(function (p) { return p && p.id !== id }).concat([{ id: id, file: file, version: item.version, integrity: item.integrity }])
await s.write('index.json', JSON.stringify(next, null, 2) + '\n')
return { ok: true, restart: true, file: file }
} catch (e) { return { ok: false, error: String((e && e.message) || e) } }
}
async function uninstall (id) {
try {
const s = store()
if (!s) return { ok: false, error: '外部插件目录不可用' }
const cur = await s.manifest()
const hit = cur.find(function (p) { return p && p.id === id })
const next = cur.filter(function (p) { return p && p.id !== id })
await s.write('index.json', JSON.stringify(next, null, 2) + '\n')
if (hit && hit.file) await s.remove(hit.file)
return { ok: true, restart: true }
} catch (e) { return { ok: false, error: String((e && e.message) || e) } }
}
global.IWBRuntimePluginMarket = { list: list, installed: installed, install: install, uninstall: uninstall }
})(typeof window !== 'undefined' ? window : globalThis)
+5
View File
@@ -169,6 +169,8 @@ function BackupModal(props) {
items.outputs = ((r && r.files) || []).map((f) => { const o = Object.assign({}, f); delete o.data; return o })
}))
await Promise.all(jobs)
// 插件(清单 + 源码)随备份走:换机器恢复后不用重装
try { const pb = (typeof window !== 'undefined') ? window.IWBRuntimePluginBackup : null; if (pb && pb.collect) { const ps = await pb.collect(); if (ps && ps.length) items.plugins = ps } } catch (e) { /* 插件快照失败不影响主备份 */ }
// 收集图片(画布引用大图 + 勾选的图库缩略图/原图)并读取数据
const refMeta = await collectBackupImages()
const galleryMeta = (bk.outputs && items.outputs) ? (await collectBackupOutputImages(items.outputs)) : []
@@ -364,6 +366,9 @@ function BackupModal(props) {
jobs.push(api('workspaces', { workspaces: mergeById((cur && cur.workspaces) || [], items.workspaces.workspaces || []), activeId: (cur && cur.activeId) || '' }))
} else jobs.push(api('workspaces', { workspaces: items.workspaces.workspaces || [], activeId: items.workspaces.activeId || '' }))
}
if (items.plugins && items.plugins.length) {
try { const pb = (typeof window !== 'undefined') ? window.IWBRuntimePluginBackup : null; if (pb && pb.restore) await pb.restore(items.plugins) } catch (e) { /* 插件还原失败不阻塞其它项 */ }
}
if (restoreSel.outputs && items.outputs) {
if (restoreMerge) {
const cur = await api('outputs').catch(() => ({ files: [] }))