43 lines
2.1 KiB
JavaScript
43 lines
2.1 KiB
JavaScript
// 插件清单纯函数:内容寻址命名 + SRI integrity。
|
||
//
|
||
// 桌面端插件清单 plugins/index.json 由 scripts/sync-plugins-from-repo.js 生成,
|
||
// 市场 zip 由 scripts/gen-market.js 生成;两条链路都依赖这里的哈希/命名规则。
|
||
// 历史上这些函数长在 scripts/plugins-publish.mjs(直写 Cloudflare KV 的网页版发布脚本),
|
||
// 网页版已停用,脚本删除,纯函数留在此处给同步脚本与测试复用。
|
||
import { createHash } from 'node:crypto'
|
||
import { basename } from 'node:path'
|
||
|
||
export const integrityOf = (buffer) => 'sha256-' + createHash('sha256').update(buffer).digest('base64')
|
||
|
||
export const idFromFile = (file) => {
|
||
const base = basename(String(file))
|
||
const m = /^plugin-([a-z][a-z0-9-]{2,31})\.js$/.exec(base)
|
||
return m ? m[1] : ''
|
||
}
|
||
|
||
// 内容寻址存储名:同 id + 同字节 ⇒ 同名(幂等);字节变 ⇒ 名变 ⇒ 客户端永不拿到陈旧缓存
|
||
export const storedNameOf = (id, buffer) => {
|
||
if (!/^[a-z][a-z0-9-]{2,31}$/.test(String(id))) throw new Error('非法插件 id:' + id)
|
||
return 'plugin-' + id + '.' + createHash('sha256').update(buffer).digest('hex').slice(0, 12) + '.js'
|
||
}
|
||
|
||
export const buildIndex = (entries) => {
|
||
const seen = new Set()
|
||
const out = []
|
||
for (const e of entries) {
|
||
if (!e || !e.id || !e.file || !e.integrity) throw new Error('清单项缺字段:' + JSON.stringify(e))
|
||
if (seen.has(e.id)) throw new Error('插件 id 重复:' + e.id)
|
||
seen.add(e.id)
|
||
out.push({ id: e.id, file: e.file, version: e.version || '', integrity: e.integrity })
|
||
}
|
||
return out.sort((a, b) => a.id.localeCompare(b.id))
|
||
}
|
||
|
||
// 并入既有清单:本次**未提供**文件的插件予以保留(incoming 同 id 覆盖旧的)。
|
||
// 2026-11-03 事故:只按传入文件重建清单 ⇒ 单发一个插件就把其余插件从清单里抹掉。
|
||
export const mergeIndexes = (existing, incoming) => {
|
||
const incomingIds = new Set(incoming.map((e) => e.id))
|
||
const kept = (Array.isArray(existing) ? existing : []).filter((e) => e && e.id && e.file && e.integrity && !incomingIds.has(e.id))
|
||
return buildIndex([...incoming, ...kept])
|
||
}
|