From cd947360c9a56eccdfaa8d5662a3b98a0c0dd699 Mon Sep 17 00:00:00 2001 From: QQ Date: Thu, 12 Nov 2026 12:12:18 +0800 Subject: [PATCH] Import client.js --- client.js | 172 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 171 insertions(+), 1 deletion(-) diff --git a/client.js b/client.js index bc3ae4c..fb6e87b 100644 --- a/client.js +++ b/client.js @@ -204,7 +204,7 @@ export function pruneFullAccess(doc) { * getSessions 每次调用现取 ctx.sessions(服务可能晚于插件就绪)。 * @returns 卸载函数 */ -export function installPermissionPolicy(doc, getSessions, timers = { setInterval, clearInterval, setTimeout, clearTimeout }) { +export function installPermissionPolicy(doc, getSessions, timers = { setInterval: (fn, ms) => setInterval(fn, ms), clearInterval: (id) => clearInterval(id), setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (id) => clearTimeout(id) }) { let disposed = false let scanTimer = 0 const scheduleScan = () => { @@ -251,6 +251,171 @@ export function installPermissionPolicy(doc, getSessions, timers = { setInterval } } + +/* ------------------------------------------------------------------ * + * 功能三:插件商店「更新」按钮。 + * + * DSH 只给官方插件原地更新;从自定义索引装的插件在发现页只有 + * 「有新版本」标签、没有按钮,只能手动卸载重装。这里补一个真按钮: + * 数据与动作都走宿主自己的远程服务——pluginMarket 查索引和安装 + * 状态,pluginManager.installBundle 按索引给出的精确 spec 覆盖 + * 安装——与官方安装流程同一套接口,不模拟点击、不动官方状态。 + * 覆盖安装在探针实测中可直接把已装旧版换成新版(changed/applied)。 + * + * 服务经子插件声明 inject 取用:主插件保持 inject 为空,审批与 + * 权限功能不依赖这些服务;未启用实验性插件索引时子插件不生效, + * 本功能静默关闭。 + * ------------------------------------------------------------------ */ + +export const UPDATE_LABELS = ['有新版本', 'Update available'] + +/** 索引条目的本地化标题在当前语言下的文本(与发现页行内展示一致)。 */ +export function localizedTitle(title, lang) { + if (typeof title === 'string') return title + if (!title || typeof title !== 'object') return '' + const chain = [lang, lang && lang.split('-')[0], 'zh-CN', 'en'] + for (const key of chain) { + if (key && typeof title[key] === 'string' && title[key]) return title[key] + } + const values = Object.values(title) + return typeof values[0] === 'string' ? values[0] : '' +} + +/** 从各索引的搜索结果里挑出「有新版本」的条目,整理成可执行的更新计划。 */ +export function pickUpdates(searchResults, lang) { + const updates = [] + for (const result of searchResults ?? []) { + const entries = result?.value?.entries ?? result?.entries ?? [] + for (const entry of entries) { + if (entry?.installation?.status !== 'update-available') continue + const versions = entry.versions ?? [] + const version = versions.find((v) => v.version === entry.defaultVersion) ?? versions[0] + const spec = version?.install?.spec + if (!entry.name || !version?.version || !spec) continue + updates.push({ + name: entry.name, + title: localizedTitle(entry.title, lang) || entry.name, + installedVersion: entry.installation.installedVersion ?? '', + version: version.version, + spec, + registry: version.install.registry, + }) + } + } + return updates +} + +/** 执行一次更新:按索引 spec 覆盖安装,宿主结果信封原样返回。 */ +export async function runUpdate(remote, update, makeRequestId) { + const requestId = makeRequestId ? makeRequestId() : 'better-chat-update-' + Date.now() + return remote.pluginManager.installBundle(update.spec, { + enabled: true, + requestId, + ...(update.registry ? { registry: update.registry } : {}), + }) +} + +/** + * 发现页里某个插件的行:状态标签本身是个按钮,从它向上找第一个 + * 同时包含插件标题、且文本总量还像一行的祖先。 + */ +export function findUpdateRow(doc, title) { + for (const el of doc.querySelectorAll('button')) { + if (!UPDATE_LABELS.includes(el.textContent?.trim())) continue + let node = el + for (let depth = 0; depth < 6 && node; depth++) { + node = node.parentElement + if (node && node.textContent?.includes(title) && node.textContent.length < 600) return node + } + } + return null +} + +/** 更新按钮的点击处理:确认 → 调宿主覆盖安装 → 按结果改按钮文案。 */ +export function makeUpdateClickHandler(doc, getRemote, update, button) { + return async (event) => { + event?.preventDefault?.() + event?.stopPropagation?.() + const view = doc.defaultView + const ask = view?.confirm ?? globalThis.confirm + const message = '更新「' + update.title + '」' + (update.installedVersion ? ' ' + update.installedVersion : '') + ' → ' + update.version + '?\n会直接覆盖安装新版,插件数据保留。' + if (ask && !ask.call(view ?? globalThis, message)) return + button.disabled = true + button.textContent = '更新中…' + try { + const result = await runUpdate(getRemote(), update, () => globalThis.crypto?.randomUUID?.() ?? undefined) + if (result?.value?.application === 'applied') { + button.textContent = '已更新,重启 DSH 后生效' + } else { + console.error('[dsh-better-chat] update failed for', update.name, result?.value?.error ?? result) + button.disabled = false + button.textContent = '更新失败,点此重试' + } + } catch (error) { + console.error('[dsh-better-chat] update failed for', update.name, error) + button.disabled = false + button.textContent = '更新失败,点此重试' + } + } +} + +/** 发现页增强:轮询索引状态,把「更新」按钮挂到有新版本的行上。 */ +export function installStoreUpdateButtons(doc, getRemote, timers = { setInterval: (fn, ms) => setInterval(fn, ms), clearInterval: (id) => clearInterval(id) }) { + let disposed = false + let updates = [] + const decorate = () => { + for (const update of updates) { + const row = findUpdateRow(doc, update.title) + if (!row || row.querySelector('[data-better-chat-update]')) continue + const button = doc.createElement('button') + button.type = 'button' + button.setAttribute('data-better-chat-update', update.name) + button.textContent = '更新到 ' + update.version + button.style.cssText = 'flex:none;margin-left:8px;padding:2px 10px;border:1px solid #7f7f7f55;border-radius:999px;background:transparent;color:inherit;font-size:12px;cursor:pointer' + button.addEventListener('click', makeUpdateClickHandler(doc, getRemote, update, button)) + row.appendChild(button) + } + } + const refresh = async () => { + try { + const remote = getRemote() + if (!remote?.pluginMarket || !remote?.pluginManager) return + const indexes = await remote.pluginMarket.listIndexes() + const urls = (indexes?.value ?? indexes ?? []).map((entry) => entry?.url).filter(Boolean) + const results = [] + for (const url of urls) { + results.push(await remote.pluginMarket.search(url, { sort: { kind: 'index' }, offset: 0, limit: 100 })) + } + if (disposed) return + updates = pickUpdates(results, doc.documentElement?.lang || 'zh-CN') + decorate() + } catch { + // 索引服务不可用(未启用实验性插件索引等):静默关闭本功能。 + } + } + const observer = new MutationObserver(() => decorate()) + observer.observe(doc.documentElement, { childList: true, subtree: true }) + const timer = timers.setInterval(() => { void refresh() }, 30000) + void refresh() + return () => { + disposed = true + observer.disconnect() + timers.clearInterval(timer) + } +} + +/** 商店更新子插件:单独声明远程服务 inject,与主功能互相隔离。 */ +const storeUpdatePlugin = { + name: 'dsh-better-chat-store-update', + inject: ['remote', 'remote.pluginMarket', 'remote.pluginManager'], + apply(childCtx) { + childCtx.effect( + () => installStoreUpdateButtons(document, () => childCtx.remote), + 'dsh-better-chat: store update buttons', + ) + }, +} + /** 本插件不硬依赖任何客户端服务(sessions 服务是可选增强,缺了只是不自动切)。 */ export const inject = [] @@ -261,4 +426,9 @@ export function apply(ctx) { () => installPermissionPolicy(document, () => ctx.sessions), 'dsh-better-chat: permission policy (no full access, auto review by default)', ) + try { + ctx.plugin(storeUpdatePlugin) + } catch { + // 子插件挂不上(旧宿主等)不影响主功能。 + } }