dsh-modpack-kit 0.2.2 → 0.2.4

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,66 @@
1
+ /**
2
+ * 附属小插件(社区资源)的宿主侧支持。
3
+ *
4
+ * 只做两件事:
5
+ * 1. 读内置清单 community/manifest.json,给 status.community 提供 builtin 信息;
6
+ * 2. 看 profile 里有没有声明兼容的外部实现(包名 dsh-modpack-community + community.json),
7
+ * 有就标成 external。外部实现只公开信息、不改主体行为,出问题也退得回内置。
8
+ */
9
+ import fs from 'node:fs'
10
+ import path from 'node:path'
11
+
12
+ export const COMMUNITY_ID = 'dsh-modpack-community'
13
+ export const COMMUNITY_API = 1
14
+
15
+ const builtinManifest = new URL('../community/manifest.json', import.meta.url)
16
+
17
+ export function readBuiltinManifest() {
18
+ try {
19
+ return JSON.parse(fs.readFileSync(builtinManifest, 'utf8'))
20
+ } catch {
21
+ return { id: COMMUNITY_ID, apiVersion: COMMUNITY_API, name: '社区资源', routes: [] }
22
+ }
23
+ }
24
+
25
+ function readExternal(profileDir) {
26
+ if (!profileDir) return null
27
+ const file = path.join(profileDir, 'node_modules', COMMUNITY_ID, 'community.json')
28
+ try {
29
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'))
30
+ if (!raw || raw.id !== COMMUNITY_ID) return null
31
+ const apiVersion = Number(raw.apiVersion)
32
+ if (!Number.isFinite(apiVersion) || apiVersion < 1) return null
33
+ return { raw, apiVersion, file }
34
+ } catch {
35
+ return null
36
+ }
37
+ }
38
+
39
+ /**
40
+ * @returns {{id: string, mode: 'builtin'|'external', apiVersion: number, version: string, enabled: boolean, reason?: string, routes: string[]}}
41
+ */
42
+ export function resolveCommunity(profileDir, config = {}) {
43
+ const builtin = readBuiltinManifest()
44
+ const enabled = config.showModpackMarket !== false
45
+ const apiVersion = Number(builtin.apiVersion) || COMMUNITY_API
46
+ const external = readExternal(profileDir)
47
+ if (external && external.apiVersion <= apiVersion) {
48
+ return {
49
+ id: COMMUNITY_ID,
50
+ mode: 'external',
51
+ apiVersion: external.apiVersion,
52
+ version: String(external.raw.version || ''),
53
+ enabled,
54
+ routes: Array.isArray(builtin.routes) ? builtin.routes : [],
55
+ }
56
+ }
57
+ return {
58
+ id: COMMUNITY_ID,
59
+ mode: 'builtin',
60
+ apiVersion,
61
+ version: '',
62
+ enabled,
63
+ ...(external ? { reason: '外部实现声明的 apiVersion 比宿主新(' + external.apiVersion + ' > ' + apiVersion + '),继续用内置实现' } : {}),
64
+ routes: Array.isArray(builtin.routes) ? builtin.routes : [],
65
+ }
66
+ }
package/lib/compat.mjs CHANGED
@@ -26,19 +26,22 @@ export function checkCompatibility(plugins, context) {
26
26
  const dshVersion = context.dshVersion || ''
27
27
  const nodeVersion = context.nodeVersion || process.versions.node
28
28
  const allow = new Set((context.config?.licenseAllow || []).map((x) => String(x).toLowerCase()))
29
+ // 建议要跟打包策略对得上:轻量包只记版本,不能说「把它一起打包进来」
30
+ const format = context.format === 'full' || context.format === 'hybrid' ? context.format : 'lite'
31
+ const canCarry = format === 'full' || format === 'hybrid'
32
+ const missingPeerSuggestion = canCarry
33
+ ? '装完可能报错或功能缺失:把这个依赖也勾进包里,或先在本机装好它。'
34
+ : '轻量包只记版本、不带别的东西,装的时候要联网取包:先在本机装好这个依赖,或改用完整包 / 混合包把依赖一起带走。'
29
35
 
30
36
  for (const plugin of plugins || []) {
31
37
  const local = installedMap.get(plugin.name)
32
38
  if (local) {
33
- if (local.version !== plugin.version) {
39
+ if (plugin.latest !== true && plugin.version && local.version !== plugin.version) {
34
40
  const cmp = compareVersions(plugin.version, local.version)
35
41
  add('info', plugin.name, 'local-version',
36
42
  '本地已装 ' + local.version + ',整合包里是 ' + plugin.version + (cmp === null ? '' : cmp > 0 ? '(较新)' : cmp < 0 ? '(较旧,可能降级)' : ''),
37
43
  cmp !== null && cmp < 0 ? '确认要降级再装;降级可能丢掉新版本的配置项。' : '安装会按整合包里的版本处理。')
38
44
  }
39
- if (!local.isBundle && plugin.isBundle) {
40
- add('warn', plugin.name, 'local-not-bundle', '本地同名包不是 DSH 插件(没有 dsh 段)', '确认整合包来源;装完可能不会出现在侧栏。')
41
- }
42
45
  } else {
43
46
  add('info', plugin.name, 'not-installed', '本地未安装,将新增', '')
44
47
  }
@@ -52,7 +55,7 @@ export function checkCompatibility(plugins, context) {
52
55
  if (!found) {
53
56
  add('warn', plugin.name, 'peer-missing-' + peer,
54
57
  '需要 ' + peer + ' ' + range + ',整合包和本机都没有',
55
- '安装后这个插件可能报错或功能缺失;把它一起打包进来。')
58
+ missingPeerSuggestion)
56
59
  continue
57
60
  }
58
61
  const ok = satisfies(found, range)
@@ -83,18 +86,16 @@ export function checkCompatibility(plugins, context) {
83
86
  }
84
87
  }
85
88
 
86
- if (!plugin.license) {
87
- add('warn', plugin.name, 'license-missing', '插件没写 license', '再分发前请联系作者确认授权,否则不要传给别人。')
88
- } else if (!allow.has(String(plugin.license).toLowerCase())) {
89
+ // 轻量包只记版本、不转手代码,这里不提许可证的事。
90
+ if (canCarry && !plugin.license) {
91
+ add('warn', plugin.name, 'license-missing', '插件没写 license', '包里带的是第三方代码,再分发前请联系作者确认授权,否则不要传给别人。')
92
+ } else if (canCarry && !allow.has(String(plugin.license).toLowerCase())) {
89
93
  add('warn', plugin.name, 'license-unlisted', 'license 不在允许列表:' + plugin.license,
90
94
  '确认许可允许再分发;不确定就只在自己机器上装。')
91
95
  }
92
96
  if (plugin.localEdits) {
93
97
  add('info', plugin.name, 'local-edits', '打包时带的是打包者改过的本地文件', '和上游发布的版本可能不一致。')
94
98
  }
95
- if (!plugin.hasClient && !plugin.hasPatch && plugin.isBundle === false) {
96
- add('warn', plugin.name, 'not-bundle', '这个包没有 dsh 段,可能不是 DSH 插件', '确认是不是装错了东西。')
97
- }
98
99
  }
99
100
 
100
101
  const errors = findings.filter((f) => f.level === 'error')
package/lib/github.mjs ADDED
@@ -0,0 +1,289 @@
1
+ import { execFile } from 'node:child_process'
2
+ import fs from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+
6
+ /**
7
+ * 只做 GitHub API 的那点事:用 curl 发请求(本机 Node 的 fetch 走代理会证书失败,
8
+ * curl 带 --ssl-no-revoke 是唯一稳的路子)。所有函数都返回解析后的 JSON。
9
+ */
10
+
11
+ const API = 'https://api.github.com'
12
+ const USER_AGENT = 'dsh-modpack-kit'
13
+
14
+ function run(args, input) {
15
+ return new Promise((resolve, reject) => {
16
+ const child = execFile('curl', args, { maxBuffer: 64 * 1024 * 1024, encoding: 'buffer' }, (error, stdout, stderr) => {
17
+ if (error) {
18
+ reject(new Error('curl 失败:' + String(error.message || error) + ' ' + String((stderr || '').toString('utf8')).slice(0, 300)))
19
+ return
20
+ }
21
+ resolve(stdout)
22
+ })
23
+ if (input !== undefined && child.stdin) {
24
+ child.stdin.end(input)
25
+ }
26
+ })
27
+ }
28
+
29
+ /** 调一次 API。method 大写,body 是对象或 undefined。 */
30
+ export async function gh(token, method, path, body) {
31
+ if (!token) throw new Error('还没有 GitHub 凭据:先在社区资源的上传页里填一次 token')
32
+ const args = [
33
+ '-sS',
34
+ '--ssl-no-revoke',
35
+ '-X', method,
36
+ '-H', 'accept: application/vnd.github+json',
37
+ '-H', 'authorization: Bearer ' + token,
38
+ '-H', 'user-agent: ' + USER_AGENT,
39
+ '-H', 'x-github-api-version: 2022-11-28',
40
+ '-w', '\n%{http_code}',
41
+ API + path,
42
+ ]
43
+ let input
44
+ if (body !== undefined) {
45
+ args.push('-H', 'content-type: application/json', '--data-binary', '@-')
46
+ input = JSON.stringify(body)
47
+ }
48
+ const out = (await run(args, input)).toString('utf8')
49
+ const index = out.lastIndexOf('\n')
50
+ const text = index >= 0 ? out.slice(0, index) : ''
51
+ const status = Number(index >= 0 ? out.slice(index + 1).trim() : '0')
52
+ let data = null
53
+ try {
54
+ data = text ? JSON.parse(text) : null
55
+ } catch {
56
+ data = null
57
+ }
58
+ if (status < 200 || status >= 300) {
59
+ const message = (data && (data.message || data.error)) || text.slice(0, 300) || 'HTTP ' + status
60
+ const error = new Error('GitHub 接口返回 ' + status + ':' + message)
61
+ error.status = status
62
+ error.data = data
63
+ throw error
64
+ }
65
+ return data
66
+ }
67
+
68
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
69
+
70
+ /** 拿到当前 token 是谁。 */
71
+ export async function whoAmI(token) {
72
+ const user = await gh(token, 'GET', '/user')
73
+ return { login: user.login, name: user.name || '' }
74
+ }
75
+
76
+ /** 确保 fork 存在(已存在就直接用),返回 fork 的 owner/name。 */
77
+ export async function ensureFork(token, catalog, login, onStep) {
78
+ const [owner, name] = String(catalog).split('/')
79
+ const forkPath = '/repos/' + login + '/' + name
80
+ try {
81
+ const repo = await gh(token, 'GET', forkPath)
82
+ if (onStep) onStep('已经有 fork:' + login + '/' + name)
83
+ return { owner: login, name, exists: true, parent: repo.parent ? repo.parent.full_name : catalog }
84
+ } catch (error) {
85
+ if (error.status !== 404) throw error
86
+ }
87
+ if (onStep) onStep('正在 fork 目录仓库…')
88
+ await gh(token, 'POST', '/repos/' + owner + '/' + name + '/forks', {})
89
+ for (let attempt = 0; attempt < 20; attempt += 1) {
90
+ await sleep(1500)
91
+ try {
92
+ const repo = await gh(token, 'GET', forkPath)
93
+ if (onStep) onStep('fork 好了:' + login + '/' + name)
94
+ return { owner: login, name, exists: false, parent: repo.parent ? repo.parent.full_name : catalog }
95
+ } catch (error) {
96
+ if (error.status !== 404) throw error
97
+ }
98
+ }
99
+ throw new Error('fork 建好后十分钟内还没出现,去 GitHub 网页上看一眼再重试')
100
+ }
101
+
102
+ /** 在一棵新分支上放两个新文件(包 + 条目),然后开 PR。 */
103
+ export async function openPackPullRequest(options) {
104
+ const { token, catalog, login, branch, packPath, packBase64, entryPath, entryText, title, body, onStep } = options
105
+ const [upstreamOwner, upstreamName] = String(catalog).split('/')
106
+ const fork = await ensureFork(token, catalog, login, onStep)
107
+ const repoPath = '/repos/' + fork.owner + '/' + fork.name
108
+
109
+ // 分支:已存在就换一个后缀,避免顶掉上一轮
110
+ let branchName = branch
111
+ let branchReady = false
112
+ for (let attempt = 0; attempt < 5; attempt += 1) {
113
+ try {
114
+ const ref = await gh(token, 'GET', repoPath + '/git/ref/heads/main')
115
+ const sha = ref.object.sha
116
+ await gh(token, 'POST', repoPath + '/git/refs', { ref: 'refs/heads/' + branchName, sha })
117
+ if (onStep) onStep('从 main 开了分支 ' + branchName)
118
+ branchReady = true
119
+ break
120
+ } catch (error) {
121
+ if (error.status === 422) {
122
+ branchName = branchName + '-' + Date.now().toString(36).slice(-4)
123
+ continue
124
+ }
125
+ throw error
126
+ }
127
+ }
128
+ if (!branchReady) throw new Error('分支建不出来(连续 5 次撞名):隔一分钟再传,或去 fork 里删几个旧分支')
129
+
130
+ // GitHub 的 contents API 对「已存在的文件」要求带 sha;我们是在新分支上写新文件,
131
+ // 撞名的唯一可能是 main 上已经有同名条目/包——提前查一次,给一句能照做的话。
132
+ const ensureFresh = async (filePath, what) => {
133
+ const encoded = String(filePath).split('/').map((part) => encodeURIComponent(part)).join('/')
134
+ try {
135
+ await gh(token, 'GET', repoPath + '/contents/' + encoded + '?ref=' + encodeURIComponent(branchName))
136
+ throw new Error('目录里已经有' + what + '(' + filePath + '):换一个包名(id 由文件名生成),或先去 ' + catalog + ' 删掉旧的那份再传')
137
+ } catch (error) {
138
+ if (error && error.status === 404) return
139
+ throw error
140
+ }
141
+ }
142
+
143
+ // 包放 Release 时 packPath 是空串:PR 里只带条目,包已经传进使用者自己的 Release
144
+ if (packPath) {
145
+ await ensureFresh(packPath, '这个包文件')
146
+
147
+ if (onStep) onStep('正在放包文件(' + Math.round(packBase64.length * 0.75 / 1024) + ' KB)…')
148
+ await gh(token, 'PUT', repoPath + '/contents/' + packPath, {
149
+ message: 'catalog: add ' + packPath.split('/').pop(),
150
+ content: packBase64,
151
+ branch: branchName,
152
+ })
153
+ }
154
+
155
+ // 封面:可选的第三份文件,放在 covers/ 下,条目里用 cover 指过来
156
+ if (options.coverPath && options.coverBase64) {
157
+ await ensureFresh(options.coverPath, '这张封面')
158
+ if (onStep) onStep('正在放封面图(' + Math.round(options.coverBase64.length * 0.75 / 1024) + ' KB)…')
159
+ await gh(token, 'PUT', repoPath + '/contents/' + options.coverPath, {
160
+ message: 'catalog: add cover for ' + (options.packId || 'pack'),
161
+ content: options.coverBase64,
162
+ branch: branchName,
163
+ })
164
+ }
165
+
166
+ if (onStep) onStep('正在写条目…')
167
+ await ensureFresh(entryPath, '这个条目')
168
+ await gh(token, 'PUT', repoPath + '/contents/' + entryPath, {
169
+ message: 'catalog: add entry ' + entryPath.split('/').pop(),
170
+ content: Buffer.from(entryText, 'utf8').toString('base64'),
171
+ branch: branchName,
172
+ })
173
+
174
+ if (onStep) onStep('正在开 PR…')
175
+ const pr = await gh(token, 'POST', '/repos/' + upstreamOwner + '/' + upstreamName + '/pulls', {
176
+ title,
177
+ head: fork.owner + ':' + branchName,
178
+ base: 'main',
179
+ body,
180
+ })
181
+ return { url: pr.html_url, number: pr.number, branch: branchName, fork: fork.owner + '/' + fork.name }
182
+ }
183
+
184
+ export function entryFileName(id) {
185
+ return 'data/packs/' + id + '.json'
186
+ }
187
+
188
+ // 只给文件名:目录仓库里放在 packs/ 下,Release 里就是资产名。
189
+ // 不要在这里带 'packs/' —— 条目里的 file 字段只认裸文件名。
190
+ export function packFileName(id, strategy) {
191
+ return id + '-' + strategy + '.dshpack'
192
+ }
193
+
194
+ /** 发一个二进制请求(Release 资产上传走 uploads.github.com,不能套 JSON 那套)。 */
195
+ function runRaw(args) {
196
+ return new Promise((resolve, reject) => {
197
+ const child = execFile('curl', args, { maxBuffer: 8 * 1024 * 1024, encoding: 'buffer' }, (error, stdout, stderr) => {
198
+ if (error) {
199
+ reject(new Error('curl 失败:' + String(error.message || error) + ' ' + String((stderr || '').toString('utf8')).slice(0, 300)))
200
+ return
201
+ }
202
+ resolve(stdout)
203
+ })
204
+ if (child.stdin) child.stdin.end()
205
+ })
206
+ }
207
+
208
+ function parseStatus(out) {
209
+ const text = out.toString('utf8')
210
+ const index = text.lastIndexOf('\n')
211
+ const body = index >= 0 ? text.slice(0, index) : ''
212
+ const status = Number(index >= 0 ? text.slice(index + 1).trim() : '0')
213
+ let data = null
214
+ try { data = body ? JSON.parse(body) : null } catch { data = null }
215
+ return { status, data, body }
216
+ }
217
+
218
+ /** 确保某个仓库里有一个叫 tag 的 Release(没有就建),返回 id。 */
219
+ export async function ensureRelease(token, repo, tag, name, onStep) {
220
+ try {
221
+ const found = await gh(token, 'GET', '/repos/' + repo + '/releases/tags/' + encodeURIComponent(tag))
222
+ if (found && found.id) {
223
+ if (onStep) onStep('已经有 Release ' + tag + ':' + (found.html_url || ''))
224
+ return { id: found.id, tag, created: false, url: found.html_url || '' }
225
+ }
226
+ } catch (error) {
227
+ if (error.status !== 404) throw error
228
+ }
229
+ const created = await gh(token, 'POST', '/repos/' + repo + '/releases', {
230
+ tag_name: tag,
231
+ name: name || tag,
232
+ body: '由 dsh-modpack-kit 上传的整合包;这个 Release 的资产下载数就是「真实下载量」。',
233
+ draft: false,
234
+ prerelease: false,
235
+ })
236
+ if (onStep) onStep('建了 Release ' + tag + ':' + (created.html_url || ''))
237
+ return { id: created.id, tag, created: true, url: created.html_url || '' }
238
+ }
239
+
240
+ /** 把包作为资产传进 Release(重名会先删旧的,免得一个 Release 里堆一串同名)。 */
241
+ export async function uploadReleaseAsset(token, repo, releaseId, name, buffer, onStep) {
242
+ const uploadUrl = 'https://uploads.github.com/repos/' + repo + '/releases/' + releaseId + '/assets?name=' + encodeURIComponent(name)
243
+ const post = async () => {
244
+ const file = path.join(os.tmpdir(), 'dshpack-asset-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8) + '.bin')
245
+ fs.writeFileSync(file, buffer)
246
+ try {
247
+ const out = await runRaw([
248
+ '-sS', '--ssl-no-revoke', '-X', 'POST',
249
+ '-H', 'accept: application/vnd.github+json',
250
+ '-H', 'authorization: Bearer ' + token,
251
+ '-H', 'user-agent: ' + USER_AGENT,
252
+ '-H', 'x-github-api-version: 2022-11-28',
253
+ '-H', 'content-type: application/octet-stream',
254
+ '--data-binary', '@' + file,
255
+ '-w', '\n%{http_code}',
256
+ uploadUrl,
257
+ ])
258
+ return parseStatus(out)
259
+ } finally {
260
+ try { fs.rmSync(file, { force: true }) } catch {}
261
+ }
262
+ }
263
+ let result = await post()
264
+ if (result.status === 422) {
265
+ // 同名资产已存在:删掉再传(GitHub 不允许覆盖资产)
266
+ try {
267
+ const rel = await gh(token, 'GET', '/repos/' + repo + '/releases/' + releaseId)
268
+ const existing = (Array.isArray(rel.assets) ? rel.assets : []).find((asset) => asset.name === name)
269
+ if (existing) {
270
+ await gh(token, 'DELETE', '/repos/' + repo + '/releases/assets/' + existing.id)
271
+ if (onStep) onStep('删掉同名旧资产,重新上传')
272
+ }
273
+ } catch {}
274
+ result = await post()
275
+ }
276
+ if (result.status < 200 || result.status >= 300) {
277
+ const message = (result.data && (result.data.message || result.data.error)) || result.body.slice(0, 300) || 'HTTP ' + result.status
278
+ const error = new Error('上传 Release 资产失败(' + result.status + '):' + message)
279
+ error.status = result.status
280
+ throw error
281
+ }
282
+ if (onStep) onStep('资产传好了:' + name + '(' + Math.round(buffer.length / 1024) + ' KB)')
283
+ return {
284
+ id: result.data && result.data.id,
285
+ name,
286
+ size: result.data && result.data.size,
287
+ url: (result.data && result.data.browser_download_url) || '',
288
+ }
289
+ }
package/lib/groups.mjs CHANGED
@@ -91,20 +91,32 @@ export function hasMarket(profileDir) {
91
91
  * @param {Record<string, string[]>} additions 组名 → 要并进去的成员
92
92
  * @returns {{changed: boolean, summary: string, error?: string}}
93
93
  */
94
- export function applyMarketGroups(profileDir, additions) {
95
- const file = marketStatePath(profileDir)
94
+ export function applyMarketGroups(profileDir, additions, options = {}) {
95
+ const stateFile = marketStatePath(profileDir)
96
+ const packKey = typeof options.packKey === 'string' ? options.packKey : ''
96
97
  let raw = {}
97
98
  try {
98
- raw = JSON.parse(fs.readFileSync(file, 'utf8'))
99
+ raw = JSON.parse(fs.readFileSync(stateFile, 'utf8'))
99
100
  } catch {
100
101
  raw = {}
101
102
  }
102
103
  if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) raw = {}
103
104
  const groups = raw.groups !== null && typeof raw.groups === 'object' && !Array.isArray(raw.groups) ? { ...raw.groups } : {}
104
105
  const order = stringList(raw.groupOrder)
106
+ const origins = raw.groupOrigins !== null && typeof raw.groupOrigins === 'object' && !Array.isArray(raw.groupOrigins) ? { ...raw.groupOrigins } : {}
105
107
  const changedParts = []
106
- for (const [name, members] of Object.entries(additions || {})) {
107
- if (!name) continue
108
+ const renames = {}
109
+ for (const [rawName, members] of Object.entries(additions || {})) {
110
+ if (!rawName) continue
111
+ let name = rawName
112
+ const owner = typeof origins[name] === 'string' ? origins[name] : ''
113
+ // 别的包已经用掉这个名字:找第一个空位,依次试「名字 2」「名字 3」……避免互相污染
114
+ if (groups[name] !== undefined && owner !== '' && packKey !== '' && owner !== packKey) {
115
+ let index = 2
116
+ while (groups[name + ' ' + index] !== undefined) index += 1
117
+ name = name + ' ' + index
118
+ renames[rawName] = name
119
+ }
108
120
  const current = stringList(groups[name])
109
121
  const merged = [...current]
110
122
  let added = 0
@@ -116,18 +128,20 @@ export function applyMarketGroups(profileDir, additions) {
116
128
  if (added === 0 && groups[name] !== undefined) continue
117
129
  groups[name] = merged
118
130
  if (!order.includes(name)) order.push(name)
131
+ if (origins[name] === undefined || origins[name] === '') origins[name] = packKey
119
132
  changedParts.push(name + '(+' + added + ')')
120
133
  }
121
- if (changedParts.length === 0) return { changed: false, summary: '' }
134
+ if (changedParts.length === 0) return { changed: false, summary: '', renames }
122
135
  raw.groups = groups
123
136
  raw.groupOrder = order
137
+ raw.groupOrigins = origins
124
138
  try {
125
- fs.mkdirSync(path.dirname(file), { recursive: true })
126
- const tmp = file + '.tmp-' + process.pid
139
+ fs.mkdirSync(path.dirname(stateFile), { recursive: true })
140
+ const tmp = stateFile + '.tmp-' + process.pid
127
141
  fs.writeFileSync(tmp, JSON.stringify(raw, null, 2) + '\n', 'utf8')
128
- fs.renameSync(tmp, file)
142
+ fs.renameSync(tmp, stateFile)
129
143
  } catch (error) {
130
- return { changed: false, summary: '', error: String((error && error.message) || error) }
144
+ return { changed: false, summary: '', renames, error: String((error && error.message) || error) }
131
145
  }
132
- return { changed: true, summary: changedParts.join('、') }
146
+ return { changed: true, summary: changedParts.join('、'), renames }
133
147
  }
package/lib/install.mjs CHANGED
@@ -185,6 +185,7 @@ export async function installPack(input) {
185
185
  const profile = targetName && targetName !== 'profiles' ? targetName : config.profile || 'desktop'
186
186
  const installed = listInstalled(profileDir)
187
187
  const compat = checkCompatibility(manifest.plugins, {
188
+ format: manifest && manifest.format,
188
189
  installed,
189
190
  dshVersion: dshVersion(profileDir),
190
191
  nodeVersion: process.versions.node,
@@ -349,7 +350,7 @@ export async function installPack(input) {
349
350
  plugin: plugin.name,
350
351
  action: 'install',
351
352
  ok: false,
352
- message: '取包失败:' + why + (/没有版本满足|notarget|E404/u.test(why) ? '(轻量包只记版本号,市场上没有这个版本时就装不回来:改用完整包或混合包,把插件本体带在包里)' : ''),
353
+ message: '取包失败:' + why + (/没有版本满足|没有版本信息|元数据缺少|registry 都失败|notarget|E404/u.test(why) ? '(轻量包只记版本号,市场上没有这个版本时就装不回来:改用完整包或混合包,把插件本体带在包里)' : ''),
353
354
  })
354
355
  continue
355
356
  }
@@ -379,7 +380,7 @@ export async function installPack(input) {
379
380
  plugin: plugin.name,
380
381
  action: 'install',
381
382
  ok: false,
382
- message: '取包失败:' + why + (/没有版本满足|notarget|E404/u.test(why) ? '(轻量包只记版本号,市场上没有这个版本时就装不回来:改用完整包或混合包,把插件本体带在包里)' : ''),
383
+ message: '取包失败:' + why + (/没有版本满足|没有版本信息|元数据缺少|registry 都失败|notarget|E404/u.test(why) ? '(轻量包只记版本号,市场上没有这个版本时就装不回来:改用完整包或混合包,把插件本体带在包里)' : ''),
383
384
  })
384
385
  continue
385
386
  }
@@ -389,6 +390,7 @@ export async function installPack(input) {
389
390
  }
390
391
 
391
392
  if (!embedded) {
393
+ if (!resolvedSpec && plugin.latest === true) resolvedSpec = plugin.name
392
394
  if (!resolvedSpec && plugin.version && String(plugin.version) !== '0.0.0') resolvedSpec = plugin.name + '@' + plugin.version
393
395
  // 轻量包本体不夹带源码,真正的代码是刚下载回来的:装之前必须补扫一遍,否则「安装前检测」是空转
394
396
  try {
@@ -433,6 +435,21 @@ export async function installPack(input) {
433
435
  if (attempt.output) lines.push(attempt.output)
434
436
  appendLog('install ' + plugin.name + ' exit=' + code + ' via=' + (usedManager ? 'manager' : 'cli') + (marketHit ? '/market' : '/pack') + (application ? ' ' + application : ''))
435
437
 
438
+ // 包里记的那一版在市场上下架了(或者本来就没这个版本号)时,先退回不带版本号的 latest 再试一次:
439
+ // 反正市场只认「是不是 file:」,记哪一版都算市场版,装最新的比装不上强。
440
+ if (code !== 0 && marketHit && marketHit.fromPack && !dir && pluginPayload(entries, plugin.dirName || plugin.name).length === 0) {
441
+ const latestAttempt = await installSpec(plugin.name, null)
442
+ if (latestAttempt.code === 0) {
443
+ lines.push('包里记的 ' + marketHit.spec + ' 装不上(退出码 ' + code + '),改按市场最新版 ' + plugin.name + ' 装上了')
444
+ code = latestAttempt.code
445
+ application = latestAttempt.application
446
+ usedManager = latestAttempt.manager
447
+ if (application === 'restart-required') restartFromManager = true
448
+ marketHit = { spec: plugin.name, version: '', fromPack: true, latest: true }
449
+ if (latestAttempt.output) lines.push(latestAttempt.output)
450
+ }
451
+ }
452
+
436
453
  // registry 这条路断了时,退回包里/本地已有的那份——能装上比装不上强,但依赖会写成 file:,
437
454
  // 插件市场会把它当成本地安装,所以下面要明确提示。
438
455
  if (code !== 0 && marketHit && marketHit.fromPack && !dir && pluginPayload(entries, plugin.dirName || plugin.name).length > 0) {
@@ -642,10 +659,13 @@ export async function installPack(input) {
642
659
  } else if (options.dryRun) {
643
660
  lines.push('演练:将把 ' + entriesText + ' 并进插件市场分组')
644
661
  } else {
645
- const applied = applyMarketGroups(profileDir, Object.fromEntries(groupAdds))
662
+ const applied = applyMarketGroups(profileDir, Object.fromEntries(groupAdds), { packKey: manifest.id || manifest.name || '' })
646
663
  if (applied.changed) {
647
- lines.push('已按包内分组并入插件市场:' + applied.summary)
648
- actions.push({ plugin: '', action: 'group', ok: true, message: '并入市场分组:' + applied.summary })
664
+ const renamed = applied.renames && Object.keys(applied.renames).length > 0
665
+ ? '(重名已避让:' + Object.entries(applied.renames).map(([from, to]) => from + ' → ' + to).join('、') + ')'
666
+ : ''
667
+ lines.push('已按包内分组并入插件市场:' + applied.summary + renamed)
668
+ actions.push({ plugin: '', action: 'group', ok: true, message: '并入市场分组:' + applied.summary + renamed })
649
669
  } else if (applied.error) {
650
670
  lines.push('市场分组没能写入(' + applied.error + ');插件已经装好,分组可以在插件市场里手动加')
651
671
  }
package/lib/manifest.mjs CHANGED
@@ -29,7 +29,9 @@ function normalizePlugin(raw) {
29
29
  }
30
30
  return {
31
31
  name,
32
- version: str(raw.version, 64) || '0.0.0',
32
+ // latest = true 表示「安装时取市场最新」,此时 version 可以为空
33
+ version: str(raw.version, 64) || (raw.latest === true ? '' : '0.0.0'),
34
+ latest: raw.latest === true,
33
35
  requested: str(raw.requested, 64),
34
36
  source: ['profile', 'npm', 'file', 'url', 'vendor'].includes(raw.source) ? raw.source : 'npm',
35
37
  registry: str(raw.registry, 300),
@@ -77,9 +77,8 @@ export function categoriesOf(raw) {
77
77
  const en = text(title && title.en) || zh
78
78
  if (zh) out.push({ id, zh, en })
79
79
  }
80
- // 顺序按内置表来,内置没有的接在后面:市场自己的顺序是声明顺序,这里保持稳定。
81
- const order = new Map(CATEGORY_FALLBACK.map((item, i) => [item.id, i]))
82
- out.sort((a, b) => (order.get(a.id) ?? 99) - (order.get(b.id) ?? 99))
80
+ // 顺序就是市场目录 metadata.categories 的声明顺序(跟插件市场界面里那一列一致);
81
+ // 内置表只在这种顺序缺失时兜底,不要拿它重排,否则两边的分类次序会对不上。
83
82
  return out.length ? out : CATEGORY_FALLBACK.slice()
84
83
  }
85
84
 
@@ -264,7 +263,12 @@ function relevance(plugin, query, tokens, categoryLabels) {
264
263
  return field(label, -10)
265
264
  }
266
265
 
267
- const compareMarket = (sort) => (a, b) => {
266
+ const compareMarket = (sort, categoryOrder) => (a, b) => {
267
+ if (sort === 'market') {
268
+ const ca = categoryOrder ? (categoryOrder.get(a.category) ?? 99) : 0
269
+ const cb = categoryOrder ? (categoryOrder.get(b.category) ?? 99) : 0
270
+ if (ca !== cb) return ca - cb
271
+ }
268
272
  if (sort === 'new') {
269
273
  const ta = Date.parse(a.publishedAt) || 0
270
274
  const tb = Date.parse(b.publishedAt) || 0
@@ -344,7 +348,9 @@ export function searchCatalog(config, input = {}) {
344
348
  if (query && score === 0) continue
345
349
  rows.push({ plugin, score, installed: true, local: local.version || '' })
346
350
  }
347
- const marketCompare = compareMarket(sort)
351
+ // 分类次序取自市场目录(index.categories 已经是市场声明顺序)
352
+ const categoryOrder = new Map(index.categories.map((c, i) => [c.id, i]))
353
+ const marketCompare = compareMarket(sort, categoryOrder)
348
354
  rows.sort((a, b) => (b.installed ? 1 : 0) - (a.installed ? 1 : 0) || b.score - a.score || marketCompare(a.plugin, b.plugin))
349
355
 
350
356
  const total = rows.length