dsh-modpack-kit 0.0.0-stage → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,197 @@
1
+ /**
2
+ * dsh-modpack —— 整合包清单(dsh-modpack.json)。
3
+ *
4
+ * 清单是整个格式的契约:读的一方只认 `schema` + `kind`,看不到就拒绝;
5
+ * 每一项都有上限,防止一个坏包把界面撑爆。
6
+ */
7
+ import { createHash } from 'node:crypto'
8
+
9
+ export const SCHEMA = 1
10
+ export const KIND = 'dsh-modpack'
11
+ export const MANIFEST_NAME = 'dsh-modpack.json'
12
+
13
+ export const sha256 = (buf) => createHash('sha256').update(buf).digest('hex')
14
+ export const shortHash = (buf) => sha256(buf).slice(0, 16)
15
+
16
+ const str = (v, max = 200) => (typeof v === 'string' ? v.slice(0, max) : '')
17
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0)
18
+ const bool = (v) => v === true
19
+
20
+ function normalizePlugin(raw) {
21
+ if (!raw || typeof raw !== 'object') throw new Error('插件条目不是对象')
22
+ const name = str(raw.name, 214)
23
+ if (!/^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/iu.test(name)) throw new Error('插件名不合法:' + name)
24
+ const config = raw.config && typeof raw.config === 'object' && !Array.isArray(raw.config) ? raw.config : null
25
+ const peers = raw.peerDependencies && typeof raw.peerDependencies === 'object' ? raw.peerDependencies : {}
26
+ const peerList = {}
27
+ for (const [key, value] of Object.entries(peers).slice(0, 100)) {
28
+ if (typeof key === 'string' && typeof value === 'string') peerList[key] = value.slice(0, 200)
29
+ }
30
+ return {
31
+ name,
32
+ version: str(raw.version, 64) || '0.0.0',
33
+ requested: str(raw.requested, 64),
34
+ source: ['profile', 'npm', 'file', 'url', 'vendor'].includes(raw.source) ? raw.source : 'npm',
35
+ registry: str(raw.registry, 300),
36
+ tarball: str(raw.tarball, 500),
37
+ integrity: str(raw.integrity, 200),
38
+ license: str(raw.license, 80),
39
+ repository: str(raw.repository, 300),
40
+ author: str(raw.author, 120),
41
+ files: num(raw.files),
42
+ size: num(raw.size),
43
+ hasClient: bool(raw.hasClient),
44
+ hasPatch: bool(raw.hasPatch),
45
+ isBundle: raw.isBundle !== false,
46
+ localEdits: bool(raw.localEdits),
47
+ // 老包没有 mode 字段,用 localEdits 兜底
48
+ mode: raw.mode === 'local' ? 'local' : raw.mode === 'base' ? 'base' : bool(raw.localEdits) ? 'local' : 'base',
49
+ configIncluded: bool(raw.configIncluded),
50
+ dataIncluded: bool(raw.dataIncluded),
51
+ peerDependencies: peerList,
52
+ engines: raw.engines && typeof raw.engines === 'object' ? raw.engines : {},
53
+ // pnpm 别名 / link 安装时目录名可能不等于包名,payload 前缀以它为准
54
+ dirName: (() => {
55
+ const value = str(raw.dirName, 200)
56
+ return /^[@A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)?$/u.test(value) ? value : ''
57
+ })(),
58
+ config,
59
+ note: str(raw.note, 300),
60
+ }
61
+ }
62
+
63
+ export function normalizeManifest(raw) {
64
+ if (!raw || typeof raw !== 'object') throw new Error('清单不是对象')
65
+ if (raw.schema !== SCHEMA) throw new Error('不支持的清单版本:' + String(raw.schema))
66
+ if (raw.kind !== KIND) throw new Error('不是 dsh 整合包:kind=' + String(raw.kind))
67
+ const plugins = Array.isArray(raw.plugins) ? raw.plugins.slice(0, 200).map(normalizePlugin) : []
68
+ if (plugins.length === 0) throw new Error('整合包里没有插件')
69
+ const seen = new Set()
70
+ for (const p of plugins) {
71
+ if (seen.has(p.name)) throw new Error('重复插件:' + p.name)
72
+ seen.add(p.name)
73
+ }
74
+ const format = raw.format === 'full' ? 'full' : 'lite'
75
+ return {
76
+ schema: SCHEMA,
77
+ kind: KIND,
78
+ format,
79
+ id: str(raw.id, 80),
80
+ name: str(raw.name, 120) || '未命名整合包',
81
+ description: str(raw.description, 2000),
82
+ author: str(raw.author, 120),
83
+ license: str(raw.license, 80),
84
+ homepage: str(raw.homepage, 300),
85
+ createdAt: str(raw.createdAt, 40) || new Date().toISOString(),
86
+ generator: {
87
+ name: str(raw.generator?.name, 80) || 'dsh-modpack',
88
+ version: str(raw.generator?.version, 40) || '0.0.0',
89
+ },
90
+ dshVersion: str(raw.dshVersion, 40),
91
+ options: {
92
+ includePayload: format === 'full',
93
+ includeConfig: raw.options ? bool(raw.options.includeConfig) : true,
94
+ includeLocalEdits: raw.options ? bool(raw.options.includeLocalEdits) : false,
95
+ keepLocalOnInstall: raw.options ? raw.options.keepLocalOnInstall !== false : true,
96
+ },
97
+ plugins,
98
+ files: Array.isArray(raw.files)
99
+ ? raw.files.slice(0, 5000).map((f) => ({ path: str(f.path, 500), sha256: str(f.sha256, 64), size: num(f.size) })).filter((f) => f.path && f.sha256)
100
+ : [],
101
+ security: {
102
+ scanned: raw.security ? raw.security.scanned === true : false,
103
+ high: num(raw.security?.high),
104
+ medium: num(raw.security?.medium),
105
+ low: num(raw.security?.low),
106
+ approvedRisk: bool(raw.security?.approvedRisk),
107
+ acknowledged: bool(raw.security?.acknowledged),
108
+ trustedOnly: bool(raw.security?.trustedOnly),
109
+ note: str(raw.security?.note, 500),
110
+ },
111
+ install: {
112
+ restartRequired: true,
113
+ notes: Array.isArray(raw.install?.notes) ? raw.install.notes.slice(0, 30).map((n) => str(n, 300)) : [],
114
+ },
115
+ extensions: raw.extensions && typeof raw.extensions === 'object' ? raw.extensions : {},
116
+ }
117
+ }
118
+
119
+ export function pluginSummary(manifest) {
120
+ return {
121
+ name: manifest.name,
122
+ format: manifest.format,
123
+ plugins: manifest.plugins.length,
124
+ createdAt: manifest.createdAt,
125
+ dshVersion: manifest.dshVersion,
126
+ bytes: manifest.files.reduce((sum, f) => sum + (f.size || 0), 0),
127
+ payloadBytes: manifest.plugins.reduce((sum, p) => sum + (p.size || 0), 0),
128
+ security: manifest.security,
129
+ }
130
+ }
131
+
132
+ /** 给人看的 README.txt:不装本插件也能照着装。 */
133
+ export function buildReadme(manifest, extra = {}) {
134
+ const lines = []
135
+ lines.push('DSH 整合包 —— ' + manifest.name)
136
+ lines.push('='.repeat(60))
137
+ if (manifest.description) {
138
+ lines.push('')
139
+ for (const line of manifest.description.split(/\r?\n/u)) lines.push(line)
140
+ }
141
+ lines.push('')
142
+ lines.push('格式:' + manifest.format + '(' + (manifest.format === 'full' ? '完整版:包含插件本体,任何工具解压即可读' : '轻量版:只有清单,需要 dsh-modpack 插件联网安装') + ')')
143
+ lines.push('生成:' + manifest.createdAt + ' 生成器:' + manifest.generator.name + ' ' + manifest.generator.version)
144
+ if (manifest.author) lines.push('打包者:' + manifest.author)
145
+ if (manifest.dshVersion) lines.push('打包时 DSH 版本:' + manifest.dshVersion)
146
+ lines.push('')
147
+ lines.push('包含的插件(' + manifest.plugins.length + ' 个)')
148
+ for (const p of manifest.plugins) {
149
+ lines.push(' · ' + p.name + '@' + p.version + (p.license ? ' [' + p.license + ']' : ' [未标注 license]') + (p.localEdits ? ' (含打包者的本地修改)' : ''))
150
+ }
151
+ lines.push('')
152
+ lines.push('安全检测')
153
+ lines.push(' 扫描:' + (manifest.security.scanned ? '已执行' : '未执行') + ',高风险 ' + manifest.security.high + ' / 中 ' + manifest.security.medium + ' / 低 ' + manifest.security.low)
154
+ lines.push(' 报告:security/report.txt(片段已打码;命中的原始内容没有落盘)')
155
+ lines.push(' 提醒:静态检测不是杀毒,未命中不代表保证安全;安装前请自行确认来源。')
156
+ lines.push('')
157
+ lines.push('怎么装')
158
+ if (manifest.format === 'lite') {
159
+ lines.push(' 方式 A(有 dsh-modpack 插件):侧栏「整合包 → 安装」选择本文件,会联网按版本取包并校验完整性。')
160
+ lines.push(' 方式 B(裸 DSH 也能装):解压后运行 install/ 里的安装器,它会按清单里的名字与版本从 registry 取包:')
161
+ lines.push(' Windows: install\\install.cmd 其它: sh install/install.sh')
162
+ lines.push(' 指定 profile 或 DSH 位置:加 --profile <名字> --dsh "<DSH 可执行文件或 cli.js>"')
163
+ } else {
164
+ lines.push(' 方式 A(推荐,有 dsh-modpack 插件):侧栏「整合包 → 安装」选择本文件,会校验完整性、')
165
+ lines.push(' 重新扫描安全项、检查兼容性,并把打包时保存的配置同步回来。')
166
+ lines.push(' 方式 B(没有任何插件、裸 DSH 也能装,推荐给没装本插件的人):')
167
+ lines.push(' 1. 解压整个 zip;')
168
+ lines.push(' 2. 运行包内安装器(需要 Node 20+):')
169
+ lines.push(' Windows: install\\install.cmd 其它: sh install/install.sh')
170
+ lines.push(' 可加参数:--profile <名字>(默认 desktop)--dry-run(只看要做什么)')
171
+ lines.push(' --no-bundles(装了但先不启用)--dsh "<DSH 可执行文件或 cli.js>"')
172
+ lines.push(' 3. 安装器会逐插件执行官方 dsh plugin add、把 configs/ 里的配置合并进 cordis.patch.yml;')
173
+ lines.push(' 4. 重启 DSH。')
174
+ lines.push(' 方式 C(手工,没有 Node 时):解压后对 plugins/ 下每个目录执行')
175
+ lines.push(' dsh plugin --profile <你的profile> add "file:<绝对路径>/plugins/<插件名>"')
176
+ lines.push(' 再把插件名加进 ~/.dsh/profiles/<你的profile>/package.json 的 dsh.profile.bundles。')
177
+ }
178
+ lines.push('')
179
+ lines.push('目录结构')
180
+ lines.push(' dsh-modpack.json 清单(机器可读,schema ' + SCHEMA + ')')
181
+ lines.push(' integrity.json 每个文件的 sha256')
182
+ lines.push(' security/ 安全检测报告(已打码)')
183
+ lines.push(' install/ 独立安装器(不依赖本插件,裸 DSH 可用)')
184
+ lines.push(' configs/ 打包时的非默认配置(每个插件一个 json)')
185
+ if (manifest.format === 'full') lines.push(' plugins/ 插件本体,一个目录一个插件')
186
+ lines.push(' data/ 插件数据快照(如果打包时选了保留)')
187
+ lines.push('')
188
+ lines.push('合规与免责')
189
+ lines.push(' · 整合包只应包含你有权再分发的插件;每个插件的 license 列在上面,')
190
+ lines.push(' 原作者的版权仍归原作者,分发前请自行确认许可条款。')
191
+ lines.push(' · 包里不包含账号凭证;打包时检测到疑似凭证的文件不会被打进去。')
192
+ lines.push(' · 不绕过任何官方渠道,不提供破解、破解依赖或规避授权的功能。')
193
+ lines.push(' · 使用前请遵守所在地法律与 B 站/DeepSeek 等平台的服务条款。')
194
+ lines.push('')
195
+ if (extra.footer) lines.push(extra.footer)
196
+ return lines.join('\n')
197
+ }
@@ -0,0 +1,419 @@
1
+ /**
2
+ * dsh-modpack —— 插件市场目录(分类 + 分页搜索)。
3
+ *
4
+ * 分类与词条都照插件市场的来:市场自己把目录发布成 npm 包 `dsh-plugin-catalog`
5
+ * (`package/plugins.json`,另有一份 CDN 上的 `index.json`),里面带 23 个分类
6
+ * 与每条插件的 `metadata.category`、版本、描述。这里只读它,不改任何东西,
7
+ * 也不替它编造分类。
8
+ *
9
+ * 读取路径按顺序回退,前一个失败才走下一个:
10
+ * 1. CDN 的 index.json(最快,一次 4~5MB)
11
+ * 2. npm 包 tarball 里的 plugins.json(与市场安装插件同一条链路)
12
+ *
13
+ * 拿到后压成一份尽量小的本地索引(描述截断、丢掉截图与埋点字段),
14
+ * 之后搜索与分页都在内存里做,页面只拿一页,不再整份下发。
15
+ */
16
+ import fs from 'node:fs'
17
+ import path from 'node:path'
18
+ import { ensureDir, pathsFor, writeJsonAtomic } from './store.mjs'
19
+ import { downloadPackage, fetchLimited } from './registry.mjs'
20
+ import { compareVersions } from './semver.mjs'
21
+
22
+ /** 市场目录的分类表。市场新增分类时,同步里会用远端那份覆盖这里。 */
23
+ export const CATEGORY_FALLBACK = [
24
+ { id: 'agi', zh: 'AGI 架构探索', en: 'AGI Architecture Exploration' },
25
+ { id: 'ui', zh: 'UI 增强', en: 'UI Enhancements' },
26
+ { id: 'usage', zh: '用量与计费', en: 'Usage & Billing' },
27
+ { id: 'theme', zh: '主题与外观', en: 'Themes & Appearance' },
28
+ { id: 'model', zh: '模型与账号接入', en: 'Models & Providers' },
29
+ { id: 'identity', zh: '身份与通信', en: 'Identity & Communication' },
30
+ { id: 'session', zh: '会话与消息', en: 'Sessions & Messages' },
31
+ { id: 'memory', zh: '记忆', en: 'Memory' },
32
+ { id: 'tools', zh: '工具与能力', en: 'Tools & Capabilities' },
33
+ { id: 'wsl', zh: 'WSL 与 Windows 互操作', en: 'WSL & Windows Interop' },
34
+ { id: 'browser', zh: '浏览器与网页', en: 'Browser & Web' },
35
+ { id: 'vision', zh: '视觉与多模态', en: 'Vision & Multimodal' },
36
+ { id: 'voice', zh: '语音与音频', en: 'Voice & Audio' },
37
+ { id: 'docs', zh: '文档与渲染', en: 'Docs & Rendering' },
38
+ { id: 'skill', zh: '技能包', en: 'Skills' },
39
+ { id: 'workflow', zh: '工作流与自动化', en: 'Workflow & Automation' },
40
+ { id: 'git', zh: 'Git 与代码评审', en: 'Git & Code Review' },
41
+ { id: 'notify', zh: '通知与集成', en: 'Notifications & Integrations' },
42
+ { id: 'dev', zh: '开发与运行时', en: 'Development & Runtime' },
43
+ { id: 'security', zh: '安全与权限', en: 'Security & Permissions' },
44
+ { id: 'remote', zh: '远程与移动端', en: 'Remote & Mobile' },
45
+ { id: 'market', zh: '插件市场与管理', en: 'Marketplace & Management' },
46
+ { id: 'fun', zh: '娱乐', en: 'Fun' },
47
+ ]
48
+
49
+ /** 目录来源,按顺序试。 */
50
+ export const CATALOG_SOURCES = [
51
+ { id: 'cdn', label: 'jsDelivr', kind: 'json', url: 'https://cdn.jsdelivr.net/npm/dsh-plugin-catalog/index.json' },
52
+ { id: 'npm', label: 'npm 包', kind: 'package', name: 'dsh-plugin-catalog' },
53
+ ]
54
+
55
+ export const CATALOG_PACKAGE = 'dsh-plugin-catalog'
56
+ export const PAGE_SIZE_DEFAULT = 20
57
+ // 索引里最多留多少条:目录现在约 1.1 万条,留 2 万够用,也不至于被超大目录拖死
58
+ const INDEX_LIMIT = 20000
59
+ const CACHE_MAX_AGE_MS = 6 * 60 * 60 * 1000
60
+
61
+ export function catalogPaths(config) {
62
+ const dir = path.join(pathsFor(config).home, 'catalog')
63
+ return { dir, index: path.join(dir, 'market.json') }
64
+ }
65
+
66
+ const text = (value) => (typeof value === 'string' ? value : value && typeof value === 'object' ? String(value.zh || value.en || value.name || value.url || '') : '')
67
+
68
+ /** 市场目录的分类映射:id -> {zh,en}。 */
69
+ export function categoriesOf(raw) {
70
+ const meta = raw && raw.metadata && typeof raw.metadata === 'object' ? raw.metadata : raw
71
+ const fromSource = meta && meta.categories && typeof meta.categories === 'object' ? meta.categories : null
72
+ if (!fromSource) return CATEGORY_FALLBACK.slice()
73
+ const out = []
74
+ for (const [id, value] of Object.entries(fromSource)) {
75
+ if (!/^[a-z][a-z0-9-]{0,31}$/u.test(id)) continue
76
+ const title = value && typeof value === 'object' && value.title && typeof value.title === 'object' ? value.title : value
77
+ const zh = text(title && title.zh) || text(value)
78
+ const en = text(title && title.en) || zh
79
+ if (zh) out.push({ id, zh, en })
80
+ }
81
+ // 顺序按内置表来,内置没有的接在后面:市场自己的顺序是声明顺序,这里保持稳定。
82
+ const order = new Map(CATEGORY_FALLBACK.map((item, i) => [item.id, i]))
83
+ out.sort((a, b) => (order.get(a.id) ?? 99) - (order.get(b.id) ?? 99))
84
+ return out.length ? out : CATEGORY_FALLBACK.slice()
85
+ }
86
+
87
+ function normalizePlugin(raw, index) {
88
+ if (!raw || typeof raw !== 'object') return null
89
+ const name = text(raw.name)
90
+ if (!name) return null
91
+ const meta = raw.metadata && typeof raw.metadata === 'object' ? raw.metadata : {}
92
+ const category = text(meta.category) || text(raw.category) || 'other'
93
+ const versions = Array.isArray(raw.versions) ? raw.versions.filter((v) => v && typeof v === 'object') : []
94
+ let latest = ''
95
+ let publishedAt = ''
96
+ for (const item of versions) {
97
+ const v = text(item.version)
98
+ if (!v) continue
99
+ latest = v
100
+ const ts = Number(item.publishTimestamp)
101
+ if (Number.isFinite(ts) && ts > 0) publishedAt = new Date(ts * 1000).toISOString()
102
+ }
103
+ const description = text(raw.description).slice(0, 360)
104
+ const repository = raw.repository && typeof raw.repository === 'object' ? text(raw.repository.url) : text(raw.repository)
105
+ const homepage = text(raw.homepage)
106
+ const keywords = Array.isArray(meta.keywords) ? meta.keywords.filter((k) => typeof k === 'string').slice(0, 8) : []
107
+ return {
108
+ name,
109
+ title: text(raw.title) || name,
110
+ description,
111
+ category,
112
+ keywords,
113
+ version: latest,
114
+ publishedAt,
115
+ homepage,
116
+ repository,
117
+ owner: text(raw.owner),
118
+ rank: index,
119
+ }
120
+ }
121
+
122
+ /** 把任意一份市场目录(CDN 的 index.json 或 npm 包的 plugins.json)压成索引。 */
123
+ export function buildIndex(raw, sourceId) {
124
+ const list = raw && Array.isArray(raw.plugins) ? raw.plugins : Array.isArray(raw) ? raw : []
125
+ const plugins = []
126
+ const cap = Math.min(list.length, INDEX_LIMIT)
127
+ for (let i = 0; i < cap; i++) {
128
+ const item = normalizePlugin(list[i], i)
129
+ if (item) plugins.push(item)
130
+ }
131
+ const categories = categoriesOf(raw)
132
+ return {
133
+ builtAt: new Date().toISOString(),
134
+ source: sourceId,
135
+ count: plugins.length,
136
+ categories,
137
+ plugins,
138
+ }
139
+ }
140
+
141
+ const memory = { key: '', data: null }
142
+
143
+ export function readIndex(config) {
144
+ const { index } = catalogPaths(config)
145
+ let stat
146
+ try { stat = fs.statSync(index) } catch { return null }
147
+ const key = index + ':' + stat.mtimeMs + ':' + stat.size
148
+ if (memory.key === key && memory.data) return memory.data
149
+ try {
150
+ const raw = JSON.parse(fs.readFileSync(index, 'utf8'))
151
+ if (!raw || !Array.isArray(raw.plugins)) return null
152
+ const data = {
153
+ builtAt: raw.builtAt || '',
154
+ source: raw.source || '',
155
+ count: raw.count || raw.plugins.length,
156
+ categories: Array.isArray(raw.categories) && raw.categories.length ? raw.categories : CATEGORY_FALLBACK.slice(),
157
+ plugins: raw.plugins,
158
+ }
159
+ memory.key = key
160
+ memory.data = data
161
+ return data
162
+ } catch {
163
+ return null
164
+ }
165
+ }
166
+
167
+ export function writeIndex(config, index) {
168
+ const { dir, index: file } = catalogPaths(config)
169
+ ensureDir(dir)
170
+ writeJsonAtomic(file, index)
171
+ return file
172
+ }
173
+
174
+ /** 分类 + 计数 + 目录是否就绪(页面首屏只读这个,很轻)。 */
175
+ export function catalogSummary(config) {
176
+ const index = readIndex(config)
177
+ const builtAt = index ? index.builtAt : ''
178
+ const built = builtAt ? Date.parse(builtAt) : 0
179
+ const stale = Boolean(built) && Date.now() - built > CACHE_MAX_AGE_MS
180
+ const counts = new Map()
181
+ if (index) {
182
+ for (const plugin of index.plugins) counts.set(plugin.category, (counts.get(plugin.category) || 0) + 1)
183
+ }
184
+ const categories = (index ? index.categories : CATEGORY_FALLBACK).map((item) => ({
185
+ id: item.id,
186
+ label: item.zh,
187
+ en: item.en,
188
+ count: counts.get(item.id) || 0,
189
+ }))
190
+ const total = index ? index.count : 0
191
+ return {
192
+ present: Boolean(index),
193
+ builtAt,
194
+ stale,
195
+ count: total,
196
+ source: index ? index.source : '',
197
+ sourceLabel: (CATALOG_SOURCES.find((s) => s.id === (index && index.source)) || {}).label || '',
198
+ categories,
199
+ total,
200
+ pageSizeDefault: PAGE_SIZE_DEFAULT,
201
+ }
202
+ }
203
+
204
+ async function fetchSource(config, source) {
205
+ if (source.kind === 'json') {
206
+ const buffer = await fetchLimited(source.url, config, { maxBytes: 128 * 1024 * 1024, timeoutMs: 120000, accept: 'application/json' })
207
+ return JSON.parse(buffer.toString('utf8'))
208
+ }
209
+ const downloaded = await downloadPackage(source.name, '', config)
210
+ const entry = downloaded.entries.find((e) => /(^|\/)plugins\.json$/u.test(e.name))
211
+ if (!entry) throw new Error(source.name + ' 里没有 plugins.json')
212
+ return JSON.parse(entry.data.toString('utf8'))
213
+ }
214
+
215
+ /**
216
+ * 拉一次市场目录并落成本地索引。
217
+ * @returns {{ok:boolean, skipped?:boolean, count?:number, source?:string, builtAt?:string, bytes?:number, ms?:number, error?:string}}
218
+ */
219
+ export async function syncCatalog(config, options = {}) {
220
+ const started = Date.now()
221
+ const existing = readIndex(config)
222
+ if (!options.force && existing && existing.builtAt) {
223
+ const age = Date.now() - Date.parse(existing.builtAt)
224
+ if (Number.isFinite(age) && age >= 0 && age < (options.maxAgeMs ?? CACHE_MAX_AGE_MS)) {
225
+ return { ok: true, skipped: true, count: existing.count, source: existing.source, builtAt: existing.builtAt, ms: Date.now() - started }
226
+ }
227
+ }
228
+ const errors = []
229
+ for (const source of CATALOG_SOURCES) {
230
+ try {
231
+ if (typeof options.onProgress === 'function') options.onProgress({ stage: 'fetch', source: source.id })
232
+ const raw = await fetchSource(config, source)
233
+ if (typeof options.onProgress === 'function') options.onProgress({ stage: 'build', source: source.id })
234
+ const index = buildIndex(raw, source.id)
235
+ if (index.count === 0) throw new Error('目录里没有插件条目')
236
+ const file = writeIndex(config, index)
237
+ const bytes = (() => { try { return fs.statSync(file).size } catch { return 0 } })(file)
238
+ memory.key = ''
239
+ return { ok: true, count: index.count, source: source.id, builtAt: index.builtAt, bytes, ms: Date.now() - started }
240
+ } catch (error) {
241
+ errors.push(source.id + ': ' + String((error && error.message) || error))
242
+ }
243
+ }
244
+ return { ok: false, error: errors.join(';') || '目录没取到', ms: Date.now() - started }
245
+ }
246
+
247
+ /** 市场式相关度:包名 > 所有者/仓库 > 描述 > 分类名。分词后要求全部命中同一字段。 */
248
+ function relevance(plugin, query, tokens, categoryLabels) {
249
+ if (!query) return 0
250
+ const field = (value, weight) => {
251
+ if (!value) return 0
252
+ const text = String(value).toLowerCase()
253
+ if (!tokens.every((token) => text.includes(token))) return 0
254
+ if (text === query) return weight + 300
255
+ if (text.includes(query)) return weight + 200
256
+ return weight + 150
257
+ }
258
+ const byName = field(plugin.name, 40)
259
+ if (byName) return byName
260
+ const byOwner = field(plugin.owner, 20) || field(plugin.repository, 10)
261
+ if (byOwner) return byOwner
262
+ const byDescription = field(plugin.description, 0)
263
+ if (byDescription) return byDescription
264
+ const label = categoryLabels.get(plugin.category) || ''
265
+ return field(label, -10)
266
+ }
267
+
268
+ const compareMarket = (sort) => (a, b) => {
269
+ if (sort === 'new') {
270
+ const ta = Date.parse(a.publishedAt) || 0
271
+ const tb = Date.parse(b.publishedAt) || 0
272
+ if (tb !== ta) return tb - ta
273
+ }
274
+ if (sort === 'name') return a.name.localeCompare(b.name)
275
+ return (a.rank ?? 0) - (b.rank ?? 0)
276
+ }
277
+
278
+ /**
279
+ * 搜一页。
280
+ * 排序:已装优先 → 市场相关度(有搜索词时)→ 市场自己的目录顺序。
281
+ * @returns {{ok:boolean, items:object[], total:number, page:number, pageSize:number, pages:number, hasMore:boolean, categories:object[], builtAt:string, source:string, error?:string}}
282
+ */
283
+ export function searchCatalog(config, input = {}) {
284
+ const index = readIndex(config)
285
+ const summary = catalogSummary(config)
286
+ const query = String(input.query || '').trim().toLowerCase()
287
+ const tokens = query.split(/\s+/u).filter(Boolean)
288
+ const category = String(input.category || 'all')
289
+ const sort = ['market', 'new', 'name'].includes(input.sort) ? input.sort : 'market'
290
+ const pageSize = Math.min(100, Math.max(5, Number(input.pageSize) || (Number(config && config.catalogPageSize) || PAGE_SIZE_DEFAULT)))
291
+ const page = Math.max(1, Number(input.page) || 1)
292
+ const installed = Array.isArray(input.installed) ? input.installed : []
293
+ const localVersion = new Map(installed.map((p) => [p.name, p.version || '']))
294
+
295
+ if (!index) {
296
+ return {
297
+ ok: false,
298
+ error: '本地还没有市场目录索引,先建立一次(5~30 秒,看网络)。',
299
+ items: [],
300
+ total: 0,
301
+ page,
302
+ pageSize,
303
+ pages: 0,
304
+ hasMore: false,
305
+ categories: summary.categories,
306
+ builtAt: '',
307
+ source: '',
308
+ }
309
+ }
310
+
311
+ const categoryLabels = new Map(index.categories.map((c) => [c.id, c.zh + ' ' + c.en]))
312
+ const labelOf = (id) => {
313
+ const hit = index.categories.find((c) => c.id === id)
314
+ if (hit) return hit.zh
315
+ return id === 'other' ? '其它' : id
316
+ }
317
+ const rows = []
318
+ const known = new Set()
319
+ for (const plugin of index.plugins) {
320
+ known.add(plugin.name)
321
+ if (category !== 'all' && plugin.category !== category) continue
322
+ const score = relevance(plugin, query, tokens, categoryLabels)
323
+ if (query && score === 0) continue
324
+ rows.push({ plugin, score, installed: localVersion.has(plugin.name), local: localVersion.get(plugin.name) || '' })
325
+ }
326
+ // 市场目录里没有的本机插件(私有插件、未发布版)照样能被搜到,否则「已装优先」会漏它们
327
+ for (const local of installed) {
328
+ if (!local || !local.name || known.has(local.name)) continue
329
+ const plugin = {
330
+ name: local.name,
331
+ title: local.name,
332
+ description: local.description || '',
333
+ category: local.category || 'other',
334
+ keywords: [],
335
+ version: local.version || '',
336
+ publishedAt: '',
337
+ homepage: '',
338
+ repository: '',
339
+ owner: '',
340
+ rank: Number.MAX_SAFE_INTEGER,
341
+ localOnly: true,
342
+ }
343
+ if (category !== 'all' && plugin.category !== category) continue
344
+ const score = relevance(plugin, query, tokens, categoryLabels)
345
+ if (query && score === 0) continue
346
+ rows.push({ plugin, score, installed: true, local: local.version || '' })
347
+ }
348
+ const marketCompare = compareMarket(sort)
349
+ rows.sort((a, b) => (b.installed ? 1 : 0) - (a.installed ? 1 : 0) || b.score - a.score || marketCompare(a.plugin, b.plugin))
350
+
351
+ const total = rows.length
352
+ const pages = Math.ceil(total / pageSize)
353
+ const start = (page - 1) * pageSize
354
+ const items = rows.slice(start, start + pageSize).map(({ plugin, installed: isLocal, local }) => ({
355
+ name: plugin.name,
356
+ title: plugin.title,
357
+ description: plugin.description,
358
+ category: plugin.category,
359
+ categoryLabel: labelOf(plugin.category),
360
+ version: plugin.version,
361
+ publishedAt: plugin.publishedAt,
362
+ homepage: plugin.homepage,
363
+ repository: plugin.repository,
364
+ owner: plugin.owner,
365
+ source: isLocal ? 'profile' : 'market',
366
+ installed: isLocal,
367
+ localVersion: local,
368
+ localOnly: plugin.localOnly === true,
369
+ updateAvailable: Boolean(isLocal && plugin.version && local && compareVersions(plugin.version, local) > 0),
370
+ }))
371
+ return {
372
+ ok: true,
373
+ items,
374
+ total,
375
+ page,
376
+ pageSize,
377
+ pages,
378
+ hasMore: start + items.length < total,
379
+ categories: summary.categories,
380
+ builtAt: index.builtAt,
381
+ source: index.source,
382
+ sort,
383
+ }
384
+ }
385
+
386
+ /** 已装插件在市场目录里属于哪一类(首屏只显示已装时用)。 */
387
+ export function categoryMapFor(config, names) {
388
+ const index = readIndex(config)
389
+ const out = {}
390
+ if (!index || !Array.isArray(names)) return out
391
+ const wanted = new Set(names)
392
+ for (const plugin of index.plugins) {
393
+ if (wanted.has(plugin.name) && !out[plugin.name]) out[plugin.name] = plugin.category
394
+ }
395
+ return out
396
+ }
397
+
398
+ /** 按名字取市场条目(首屏给已装插件补上「市场同名版」信息,只读)。 */
399
+ export function lookupPlugins(config, names) {
400
+ const index = readIndex(config)
401
+ const out = {}
402
+ if (!index || !Array.isArray(names)) return out
403
+ const wanted = new Set(names)
404
+ for (const plugin of index.plugins) {
405
+ if (!wanted.has(plugin.name) || out[plugin.name]) continue
406
+ out[plugin.name] = {
407
+ name: plugin.name,
408
+ title: plugin.title,
409
+ description: plugin.description,
410
+ category: plugin.category,
411
+ version: plugin.version,
412
+ homepage: plugin.homepage,
413
+ repository: plugin.repository,
414
+ }
415
+ }
416
+ return out
417
+ }
418
+
419
+ export const catalogLimits = { indexLimit: INDEX_LIMIT, maxBytes: 24 * 1024 * 1024 }