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,274 @@
1
+ /**
2
+ * dsh-modpack —— 只读 + 受控写入 DSH profile。
3
+ *
4
+ * 读:profile/package.json、bundles 列表、node_modules 里已装插件、DSH 版本。
5
+ * 写:只有三处,且每处先备份——
6
+ * 1. package.json 的 `dsh.profile.bundles`(让 DSH 下次启动加载整合包里的插件);
7
+ * 2. cordis.patch.yml 里按 id 覆盖单条配置(只改那一条,其他字节不动);
8
+ * 3. 调用官方 CLI `dsh plugin --profile <p> add …` 装包(和插件市场同一条路径)。
9
+ */
10
+ import fs from 'node:fs'
11
+ import path from 'node:path'
12
+ import { spawn } from 'node:child_process'
13
+ import { writeJsonAtomic, appendLog } from './store.mjs'
14
+
15
+ export function readJson(file, fallback = null) {
16
+ try {
17
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
18
+ } catch {
19
+ return fallback
20
+ }
21
+ }
22
+
23
+ export function readProfilePackage(profileDir) {
24
+ return readJson(path.join(profileDir, 'package.json'), null)
25
+ }
26
+
27
+ export function listInstalled(profileDir) {
28
+ const modulesDir = path.join(profileDir, 'node_modules')
29
+ const out = []
30
+ let dirents
31
+ try {
32
+ dirents = fs.readdirSync(modulesDir, { withFileTypes: true })
33
+ } catch {
34
+ return out
35
+ }
36
+ const push = (dir, namePrefix) => {
37
+ const name = namePrefix ? namePrefix + '/' + dir : dir
38
+ const dirPath = path.join(modulesDir, name)
39
+ const pkg = readJson(path.join(dirPath, 'package.json'), null)
40
+ if (!pkg || typeof pkg !== 'object') return
41
+ let real = dirPath
42
+ try { real = fs.realpathSync(dirPath) } catch {}
43
+ let size = 0
44
+ try {
45
+ const stat = fs.statSync(real)
46
+ size = stat.isDirectory() ? 0 : stat.size
47
+ } catch {}
48
+ out.push({
49
+ name: typeof pkg.name === 'string' ? pkg.name : name,
50
+ dirName: name,
51
+ version: typeof pkg.version === 'string' ? pkg.version : '0.0.0',
52
+ dir: dirPath,
53
+ realDir: real,
54
+ pkg,
55
+ isBundle: Boolean(pkg.dsh && (pkg.dsh.bundle || pkg.dsh.client)),
56
+ hasClient: Boolean(pkg.dsh && pkg.dsh.client) || Boolean(pkg.exports && (pkg.exports['./client'] || pkg.exports['./client.js'])),
57
+ hasPatch: Boolean(pkg.dsh && pkg.dsh.bundle && pkg.dsh.bundle.patch),
58
+ // 是不是"给 DSH 用的插件",而不是某个插件的传递依赖
59
+ description: typeof pkg.description === 'string' ? pkg.description.slice(0, 300) : '',
60
+ isPlugin: Boolean(
61
+ pkg.dsh
62
+ || (Array.isArray(pkg.keywords) && pkg.keywords.includes('dsh-plugin'))
63
+ || /^(?:@[^/]+\/)?dsh[-.]/u.test(name),
64
+ ),
65
+ size,
66
+ })
67
+ }
68
+ for (const dirent of dirents) {
69
+ if (!dirent.isDirectory() && !dirent.isSymbolicLink()) continue
70
+ if (dirent.name.startsWith('.')) continue
71
+ if (dirent.name.startsWith('@')) {
72
+ let scoped = []
73
+ try { scoped = fs.readdirSync(path.join(modulesDir, dirent.name), { withFileTypes: true }) } catch {}
74
+ for (const sub of scoped) {
75
+ if (sub.isDirectory() || sub.isSymbolicLink()) push(sub.name, dirent.name)
76
+ }
77
+ continue
78
+ }
79
+ push(dirent.name, '')
80
+ }
81
+ out.sort((a, b) => (a.isBundle === b.isBundle ? a.name.localeCompare(b.name) : a.isBundle ? -1 : 1))
82
+ return out
83
+ }
84
+
85
+ export function dshVersion(profileDir) {
86
+ for (const name of ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app']) {
87
+ const pkg = readJson(path.join(profileDir, 'node_modules', name, 'package.json'), null)
88
+ if (pkg && typeof pkg.version === 'string') return pkg.version
89
+ }
90
+ return ''
91
+ }
92
+
93
+ export function readBundles(profilePkg) {
94
+ const list = profilePkg && profilePkg.dsh && profilePkg.dsh.profile && profilePkg.dsh.profile.bundles
95
+ return Array.isArray(list) ? list.filter((x) => typeof x === 'string') : []
96
+ }
97
+
98
+ function backup(file) {
99
+ if (!fs.existsSync(file)) return ''
100
+ const stamp = new Date().toISOString().replace(/[:.]/gu, '-')
101
+ const target = file + '.bak-modpack-' + stamp
102
+ fs.copyFileSync(file, target)
103
+ return target
104
+ }
105
+
106
+ /** 把名字补进 bundles 列表;已存在就什么都不做。返回 {changed, backup, added}。 */
107
+ export function ensureBundles(profileDir, names) {
108
+ const file = path.join(profileDir, 'package.json')
109
+ const pkg = readProfilePackage(profileDir)
110
+ if (!pkg) throw new Error('profile/package.json 读不到:' + file)
111
+ if (!pkg.dsh) pkg.dsh = {}
112
+ if (!pkg.dsh.profile) pkg.dsh.profile = {}
113
+ if (!Array.isArray(pkg.dsh.profile.bundles)) pkg.dsh.profile.bundles = []
114
+ const added = []
115
+ for (const name of names) {
116
+ if (!name || typeof name !== 'string') continue
117
+ if (!pkg.dsh.profile.bundles.includes(name)) {
118
+ pkg.dsh.profile.bundles.push(name)
119
+ added.push(name)
120
+ }
121
+ }
122
+ if (added.length === 0) return { changed: false, backup: '', added }
123
+ const bak = backup(file)
124
+ writeJsonAtomic(file, pkg)
125
+ return { changed: true, backup: bak, added }
126
+ }
127
+
128
+ /** 把 bundles 精确恢复成给定列表(CLI 自己也会登记,装好先不启用时用它撤回)。返回是否改过。 */
129
+ export function setBundles(profileDir, names) {
130
+ const file = path.join(profileDir, 'package.json')
131
+ const pkg = readProfilePackage(profileDir)
132
+ if (!pkg) throw new Error('profile/package.json 读不到:' + file)
133
+ const want = names.filter((x) => typeof x === 'string')
134
+ const now = readBundles(pkg)
135
+ if (now.length === want.length && now.every((x, i) => x === want[i])) return false
136
+ if (!pkg.dsh) pkg.dsh = {}
137
+ if (!pkg.dsh.profile) pkg.dsh.profile = {}
138
+ pkg.dsh.profile.bundles = want
139
+ backup(file)
140
+ writeJsonAtomic(file, pkg)
141
+ return true
142
+ }
143
+
144
+ export function patchPath(profileDir) {
145
+ return path.join(profileDir, 'cordis.patch.yml')
146
+ }
147
+
148
+ export function readPatch(profileDir) {
149
+ try {
150
+ return fs.readFileSync(patchPath(profileDir), 'utf8')
151
+ } catch {
152
+ return ''
153
+ }
154
+ }
155
+
156
+ /** 原子写补丁文件,返回备份路径。 */
157
+ export function writePatch(profileDir, text) {
158
+ const file = patchPath(profileDir)
159
+ const bak = backup(file)
160
+ const tmp = file + '.' + Date.now() + '.tmp'
161
+ fs.writeFileSync(tmp, text, 'utf8')
162
+ fs.renameSync(tmp, file)
163
+ return bak
164
+ }
165
+
166
+ function cliPath() {
167
+ if (process.env.DSH_CLI) return process.env.DSH_CLI
168
+ const root = path.dirname(process.execPath)
169
+ return path.join(root, 'resources', 'runtime', 'cli', 'bin', 'dsh.cmd')
170
+ }
171
+
172
+ /** 宿主自带的 CLI 入口(app.asar 里的 cli.js);有它就不用走 .cmd,省掉 cmd 的引号与编码问题。 */
173
+ function cliEntry() {
174
+ const roots = []
175
+ if (process.resourcesPath) roots.push(process.resourcesPath)
176
+ try { roots.push(path.join(path.dirname(process.execPath), 'resources')) } catch {}
177
+ for (const root of roots) {
178
+ if (!root) continue
179
+ const js = path.join(root, 'app.asar', 'dsh', 'node_modules', '@deepseek-ai', 'dsh-desktop-host', 'lib', 'cli.js')
180
+ try { if (fs.existsSync(js)) return js } catch {}
181
+ }
182
+ return ''
183
+ }
184
+
185
+ function quoteArg(arg) {
186
+ if (/[&|<>^%!"\r\n\u0000-\u001f]/u.test(arg)) throw new Error('安装参数含不允许的字符:' + arg)
187
+ return /\s/u.test(arg) ? '"' + arg + '"' : arg
188
+ }
189
+
190
+ /** argv 直传时只挡控制字符与双引号;中文用户名、`Program Files (x86)` 这类路径照常放行。 */
191
+ function safeArg(arg) {
192
+ return typeof arg === 'string' && arg.length > 0 && arg.length < 4096 && !/[\u0000-\u001f"]/u.test(arg)
193
+ }
194
+
195
+ /** 允许调用方连 `plugin --profile x` 一起传(install.mjs 就是那么传的),这里统一剥成纯 pnpm 参数。 */
196
+ function normalizePluginArgs(args) {
197
+ const list = []
198
+ for (let i = 0; i < args.length; i += 1) {
199
+ const arg = args[i]
200
+ if (arg === 'plugin') continue
201
+ if (arg === '--profile') { i += 1; continue }
202
+ list.push(arg)
203
+ }
204
+ return list
205
+ }
206
+
207
+ /** Windows 下的 CLI 输出是 GBK,直接按 UTF-8 解会把中文变乱码;乱码率过高时换 GBK 再解。 */
208
+ function decodeOutput(buffer) {
209
+ const utf8 = buffer.toString('utf8')
210
+ if (!utf8.includes('\uFFFD')) return utf8
211
+ try {
212
+ const gbk = new TextDecoder('gbk', { fatal: false }).decode(buffer)
213
+ return gbk.includes('\uFFFD') ? utf8 : gbk
214
+ } catch { return utf8 }
215
+ }
216
+
217
+ /**
218
+ * 调官方 CLI(内部就是 pnpm),和插件市场安装走同一条路。
219
+ * 优先直接起 exe + cli.js:参数不经 cmd,引号与中文编码都不会被吞;找不到才退回 .cmd。
220
+ * @returns {Promise<{code: number, output: string}>}
221
+ */
222
+ export function runDshPlugin(profile, args, options = {}) {
223
+ return new Promise((resolve, reject) => {
224
+ if (!/^[A-Za-z0-9_-]{1,64}$/u.test(profile)) { reject(new Error('profile 名不合法')); return }
225
+ for (const arg of args) if (!safeArg(arg)) { reject(new Error('参数含不允许的字符:' + arg)); return }
226
+ const pluginArgs = normalizePluginArgs(args)
227
+ const entry = cliEntry()
228
+ const env = { ...process.env, CI: '1' }
229
+ let child
230
+ if (entry) {
231
+ env.ELECTRON_RUN_AS_NODE = '1'
232
+ child = spawn(process.execPath, ['--expose-internals', entry, 'plugin', '--profile', profile, ...pluginArgs], {
233
+ cwd: options.cwd,
234
+ windowsHide: true,
235
+ env,
236
+ })
237
+ } else {
238
+ const cli = cliPath()
239
+ if (!fs.existsSync(cli)) { reject(new Error('找不到 DSH CLI:' + cli)); return }
240
+ const comspec = process.env.ComSpec || 'C:\\Windows\\System32\\cmd.exe'
241
+ // cmd 回退:整串用一对引号包住,/s 只会剥掉最外层那一对,里面的 "cli" 才守得住
242
+ const command = '""' + cli + '" plugin --profile ' + profile + ' ' + pluginArgs.map(quoteArg).join(' ') + '"'
243
+ child = spawn(comspec, ['/d', '/s', '/c', command], {
244
+ cwd: options.cwd,
245
+ windowsHide: true,
246
+ env,
247
+ windowsVerbatimArguments: true,
248
+ })
249
+ }
250
+ let buffer = Buffer.alloc(0)
251
+ let output = ''
252
+ const append = (chunk) => {
253
+ buffer = Buffer.concat([buffer, chunk])
254
+ if (buffer.length > 400000) buffer = buffer.subarray(buffer.length - 400000)
255
+ output = decodeOutput(buffer)
256
+ if (output.length > 200000) output = output.slice(-200000)
257
+ if (options.onLine) {
258
+ for (const line of output.split(/\r?\n/u).slice(-4)) options.onLine(line)
259
+ }
260
+ }
261
+ child.stdout.on('data', append)
262
+ child.stderr.on('data', append)
263
+ const timer = setTimeout(() => {
264
+ try { child.kill('SIGKILL') } catch {}
265
+ reject(new Error('安装超时(' + Math.round((options.timeoutMs ?? 300000) / 1000) + ' 秒):' + output.slice(-2000)))
266
+ }, options.timeoutMs ?? 300000)
267
+ child.on('error', (error) => { clearTimeout(timer); reject(error) })
268
+ child.on('close', (code) => {
269
+ clearTimeout(timer)
270
+ appendLog('cli ' + args.join(' ') + ' -> ' + code + ' :: ' + output.slice(-400).replace(/\n/gu, ' | '))
271
+ resolve({ code: code ?? -1, output })
272
+ })
273
+ })
274
+ }
@@ -0,0 +1,223 @@
1
+ /**
2
+ * dsh-modpack —— 从 npm / 插件市场源取包。
3
+ *
4
+ * 只信任 https;主机名必须在 allowHosts 里;重定向每一跳都重新校验
5
+ * (不然一个 302 就能把请求带到任意地址)。下载有体积上限,拿到 tarball
6
+ * 后先核对 registry 给的 sha512,再解包。
7
+ */
8
+ import { createHash } from 'node:crypto'
9
+ import { readTarball, stripPackagePrefix } from './tar.mjs'
10
+ import { parseVersion, satisfies, compareVersions } from './semver.mjs'
11
+
12
+ const NAME_RE = /^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/iu
13
+ const TIMEOUT_MS = 30000
14
+
15
+ export function assertAllowedUrl(url, config) {
16
+ let parsed
17
+ try {
18
+ parsed = new URL(url)
19
+ } catch {
20
+ throw new Error('地址无法解析:' + String(url).slice(0, 200))
21
+ }
22
+ if (parsed.protocol !== 'https:') throw new Error('只允许 https 地址:' + parsed.protocol)
23
+ const host = parsed.hostname.toLowerCase()
24
+ const allowed = Array.isArray(config?.allowHosts) && config.allowHosts.length > 0 ? config.allowHosts : ['registry.npmjs.org']
25
+ if (!allowed.some((h) => host === h.toLowerCase() || host.endsWith('.' + h.toLowerCase()))) {
26
+ throw new Error('主机不在允许列表:' + host + '(可在设置里添加)')
27
+ }
28
+ return parsed
29
+ }
30
+
31
+ /** 手工跟重定向,每一跳都校验主机与协议。 */
32
+ export async function fetchLimited(url, config, options = {}) {
33
+ const maxBytes = options.maxBytes ?? config?.maxDownloadBytes ?? 128 * 1024 * 1024
34
+ let current = url
35
+ for (let hop = 0; hop < 6; hop += 1) {
36
+ assertAllowedUrl(current, config)
37
+ const res = await fetch(current, {
38
+ redirect: 'manual',
39
+ signal: AbortSignal.timeout(options.timeoutMs ?? TIMEOUT_MS),
40
+ headers: { 'user-agent': 'dsh-modpack', accept: options.accept ?? '*/*' },
41
+ })
42
+ if (res.status >= 300 && res.status < 400) {
43
+ const location = res.headers.get('location')
44
+ if (!location) throw new Error('重定向没有 location:' + current)
45
+ current = new URL(location, current).href
46
+ continue
47
+ }
48
+ if (!res.ok) throw new Error('HTTP ' + res.status + ':' + current)
49
+ const length = Number(res.headers.get('content-length') || '0')
50
+ if (length > maxBytes) throw new Error('响应体过大(' + length + ' 字节)')
51
+ if (!res.body) return Buffer.alloc(0)
52
+ const chunks = []
53
+ let total = 0
54
+ const reader = res.body.getReader()
55
+ for (;;) {
56
+ const { done, value } = await reader.read()
57
+ if (done) break
58
+ total += value.length
59
+ if (total > maxBytes) {
60
+ try { await reader.cancel() } catch {}
61
+ throw new Error('下载超过上限(' + maxBytes + ' 字节)')
62
+ }
63
+ chunks.push(Buffer.from(value))
64
+ }
65
+ return Buffer.concat(chunks)
66
+ }
67
+ throw new Error('重定向次数过多:' + url)
68
+ }
69
+
70
+ export async function fetchJson(url, config, options = {}) {
71
+ const buf = await fetchLimited(url, config, { ...options, maxBytes: options.maxBytes ?? 16 * 1024 * 1024, accept: 'application/json' })
72
+ try {
73
+ return JSON.parse(buf.toString('utf8'))
74
+ } catch {
75
+ throw new Error('返回内容不是 JSON:' + url)
76
+ }
77
+ }
78
+
79
+ export function validatePackageName(name) {
80
+ if (typeof name !== 'string' || name.length > 214 || !NAME_RE.test(name)) {
81
+ throw new Error('不是合法的 npm 包名:' + String(name).slice(0, 80))
82
+ }
83
+ return name
84
+ }
85
+
86
+ /** 依次尝试每个 registry,第一个成功的算。 */
87
+ export async function npmMetadata(name, config) {
88
+ validatePackageName(name)
89
+ const registries = Array.isArray(config?.registries) && config.registries.length > 0
90
+ ? config.registries
91
+ : ['https://registry.npmjs.org']
92
+ const errors = []
93
+ for (const base of registries) {
94
+ try {
95
+ const url = base.replace(/\/+$/u, '') + '/' + encodeURIComponent(name).replace(/^%40/u, '@')
96
+ const meta = await fetchJson(url, config, { accept: 'application/json' })
97
+ if (!meta || typeof meta !== 'object' || !meta.versions) throw new Error('元数据缺少 versions')
98
+ return { meta, registry: base.replace(/\/+$/u, '') }
99
+ } catch (error) {
100
+ errors.push(base + ' → ' + String(error?.message || error))
101
+ }
102
+ }
103
+ throw new Error('registry 都失败了:' + errors.join(';'))
104
+ }
105
+
106
+ /** 选版本:精确版 > dist-tags.latest > 范围里最高的稳定版。 */
107
+ export function pickVersion(meta, spec) {
108
+ const versions = Object.keys(meta.versions || {})
109
+ if (versions.length === 0) throw new Error('该包没有任何版本')
110
+ const wanted = typeof spec === 'string' && spec.trim() !== '' && spec !== 'latest' ? spec.trim() : ''
111
+ if (wanted && meta.versions[wanted]) return wanted
112
+ if (!wanted) {
113
+ const latest = meta['dist-tags'] && meta['dist-tags'].latest
114
+ if (latest && meta.versions[latest]) return latest
115
+ }
116
+ const candidates = versions
117
+ .filter((v) => (wanted ? satisfies(v, wanted) === true : true))
118
+ .sort((a, b) => (compareVersions(b, a) ?? 0))
119
+ if (candidates.length === 0) throw new Error('没有版本满足「' + (wanted || 'latest') + '」')
120
+ const stable = candidates.find((v) => !parseVersion(v)?.pre)
121
+ return stable || candidates[0]
122
+ }
123
+
124
+ export function relativeTime(iso) {
125
+ const t = Date.parse(iso)
126
+ if (!Number.isFinite(t)) return ''
127
+ const days = Math.round((Date.now() - t) / 86400000)
128
+ return days <= 0 ? '今天' : days + ' 天前'
129
+ }
130
+
131
+ /**
132
+ * 下载并解析一个 npm 包。
133
+ * @returns {Promise<{name, version, registry, tarball, integrity, sha256, license, repository, pkg, entries, files, unpackedBytes}>}
134
+ */
135
+ export async function downloadPackage(name, spec, config) {
136
+ const { meta, registry } = await npmMetadata(name, config)
137
+ const version = pickVersion(meta, spec)
138
+ const manifest = meta.versions[version]
139
+ if (!manifest || !manifest.dist || !manifest.dist.tarball) throw new Error('版本 ' + version + ' 没有 tarball')
140
+ const tarballUrl = new URL(manifest.dist.tarball, registry + '/').href
141
+ assertAllowedUrl(tarballUrl, config)
142
+ const tgz = await fetchLimited(tarballUrl, config, { maxBytes: config?.maxDownloadBytes })
143
+ const expected = typeof manifest.dist.integrity === 'string' ? manifest.dist.integrity : ''
144
+ if (expected.startsWith('sha512-')) {
145
+ const actual = 'sha512-' + createHash('sha512').update(tgz).digest('base64')
146
+ if (actual !== expected) throw new Error('tarball 校验失败(sha512 不符):' + name + '@' + version)
147
+ }
148
+ const entries = stripPackagePrefix(readTarball(tgz))
149
+ const pkgEntry = entries.find((e) => e.name === 'package.json')
150
+ if (!pkgEntry) throw new Error('包里没有 package.json:' + name)
151
+ let pkg
152
+ try {
153
+ pkg = JSON.parse(pkgEntry.data.toString('utf8'))
154
+ } catch {
155
+ throw new Error('package.json 不是合法 JSON:' + name)
156
+ }
157
+ return {
158
+ name: pkg.name || name,
159
+ version: pkg.version || version,
160
+ registry,
161
+ tarball: tarballUrl,
162
+ integrity: expected,
163
+ sha256: 'sha256-' + createHash('sha256').update(tgz).digest('hex'),
164
+ license: typeof pkg.license === 'string' ? pkg.license : (pkg.license && pkg.license.type) || '',
165
+ repository: typeof pkg.repository === 'string' ? pkg.repository : (pkg.repository && pkg.repository.url) || '',
166
+ pkg,
167
+ entries,
168
+ unpackedBytes: entries.reduce((sum, e) => sum + e.data.length, 0),
169
+ }
170
+ }
171
+
172
+ /** 市场目录(awesome-dsh-plugin.com),失败就返回空——它只是锦上添花。 */
173
+ /**
174
+ * 插件市场目录。官方站点在国内经常连不上或极慢,所以:
175
+ * 先试官方 JSON(短超时,不让页面干等),失败就退回 npm 搜索。
176
+ * 两条路都失败时返回空数组,调用方展示"目录不可用"而不是白屏。
177
+ */
178
+ export async function fetchCatalog(config) {
179
+ try {
180
+ const data = await fetchJson('https://awesome-dsh-plugin.com/plugins.json', config, {
181
+ maxBytes: 8 * 1024 * 1024,
182
+ timeoutMs: 8000,
183
+ })
184
+ const list = Array.isArray(data) ? data : (Array.isArray(data?.plugins) ? data.plugins : [])
185
+ if (list.length > 0) return list
186
+ } catch {
187
+ // 站点慢/被挡,走 npm 兜底
188
+ }
189
+ return npmSearchCatalog(config)
190
+ }
191
+
192
+ /** npm 搜索兜底:以 keywords 找同类插件,字段摊平成官方目录的近似形状。 */
193
+ export async function npmSearchCatalog(config) {
194
+ const queries = ['keywords:dsh-plugin', 'keywords:dsh-bundle']
195
+ const seen = new Map()
196
+ for (const text of queries) {
197
+ const url = 'https://registry.npmjs.org/-/v1/search?size=250&text=' + encodeURIComponent(text)
198
+ try {
199
+ const data = await fetchJson(url, config, { maxBytes: 8 * 1024 * 1024, timeoutMs: 20000 })
200
+ const objects = Array.isArray(data?.objects) ? data.objects : []
201
+ for (const entry of objects) {
202
+ const pkg = entry && entry.package
203
+ if (!pkg || !pkg.name || seen.has(pkg.name)) continue
204
+ const repo = pkg.links?.repository || (pkg.repository && (pkg.repository.url || pkg.repository)) || ''
205
+ const author = pkg.author && typeof pkg.author === 'object' ? pkg.author.name || '' : pkg.author || ''
206
+ seen.set(pkg.name, {
207
+ name: pkg.name,
208
+ title: pkg.name,
209
+ description: String(pkg.description || ''),
210
+ version: String(pkg.version || ''),
211
+ author: String(author || ''),
212
+ repository: String(repo || ''),
213
+ license: String(pkg.license || ''),
214
+ tags: Array.isArray(pkg.keywords) ? pkg.keywords.slice(0, 10) : [],
215
+ source: 'npm-search',
216
+ })
217
+ }
218
+ } catch {
219
+ // 单个查询失败不影响另一个
220
+ }
221
+ }
222
+ return [...seen.values()]
223
+ }