dsh-remote-plugin 0.8.2 → 0.8.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.
Files changed (122) hide show
  1. package/README.md +1 -1
  2. package/apk/dsh-remote.apk +0 -0
  3. package/approval-summary.mjs +115 -0
  4. package/gateway.cjs +708 -70
  5. package/index.mjs +12 -0
  6. package/insights.mjs +6 -4
  7. package/market.mjs +4 -1
  8. package/package.json +2 -1
  9. package/plugin-center.mjs +208 -24
  10. package/plugin-transaction.mjs +29 -6
  11. package/public/admin.html +33 -34
  12. package/public/admin.js +12 -24
  13. package/public/announcements.json +31 -0
  14. package/public/app.js +99 -80
  15. package/public/approval-summary.js +78 -0
  16. package/public/build.json +2 -2
  17. package/public/cache-upgrade.js +51 -0
  18. package/public/chat-copy.js +59 -0
  19. package/public/desktop/desktop.css +23 -34
  20. package/public/desktop/desktop.html +83 -96
  21. package/public/desktop/desktop.js +68 -51
  22. package/public/e2ee-transport.js +147 -0
  23. package/public/extensions.js +6 -6
  24. package/public/history.js +88 -6
  25. package/public/image-cache.js +141 -0
  26. package/public/image-preview.js +48 -5
  27. package/public/index.html +86 -104
  28. package/public/md.js +39 -15
  29. package/public/motion.js +1 -1
  30. package/public/plugin-center.css +1 -0
  31. package/public/plugin-center.js +93 -12
  32. package/public/plugin.html +27 -20
  33. package/public/relay-devices.js +74 -0
  34. package/public/relay-settings.css +7 -0
  35. package/public/relay-settings.js +17 -9
  36. package/public/session-deck.css +7 -1
  37. package/public/session-deck.js +1 -1
  38. package/public/skins/blue-fish/DESIGN.md +24 -0
  39. package/public/skins/blue-fish/preview.html +12 -289
  40. package/public/skins/blue-fish/skin.css +95 -585
  41. package/public/skins/blue-fish/sparkles.svg +18 -0
  42. package/public/skins/bocchi/DESIGN.md +99 -0
  43. package/public/skins/bocchi/face.png +0 -0
  44. package/public/skins/bocchi/grain.png +0 -0
  45. package/public/skins/bocchi/icon-blush.png +0 -0
  46. package/public/skins/bocchi/icon-sleep.png +0 -0
  47. package/public/skins/bocchi/icon-smile.png +0 -0
  48. package/public/skins/bocchi/icon-star.png +0 -0
  49. package/public/skins/bocchi/icon-wink.png +0 -0
  50. package/public/skins/bocchi/icon.png +0 -0
  51. package/public/skins/bocchi/pattern-soft.png +0 -0
  52. package/public/skins/bocchi/pattern.png +0 -0
  53. package/public/skins/bocchi/preview.html +55 -0
  54. package/public/skins/bocchi/skin.css +233 -0
  55. package/public/skins/bocchi/stage-bg.png +0 -0
  56. package/public/skins/bocchi/stage-soft.png +0 -0
  57. package/public/skins/bocchi/stand.png +0 -0
  58. package/public/skins/bocchi/sticker-guitar.png +0 -0
  59. package/public/skins/kessoku/DESIGN.md +38 -0
  60. package/public/skins/kessoku/grain.png +0 -0
  61. package/public/skins/kessoku/skin.css +212 -0
  62. package/public/skins/kita/SOURCES.json +51 -0
  63. package/public/skins/kita/face.png +0 -0
  64. package/public/skins/kita/icon-live.png +0 -0
  65. package/public/skins/kita/icon-reddress.png +0 -0
  66. package/public/skins/kita/icon-seifuku.png +0 -0
  67. package/public/skins/kita/pattern.png +0 -0
  68. package/public/skins/kita/preview.html +56 -0
  69. package/public/skins/kita/skin.css +26 -0
  70. package/public/skins/kita/stand.png +0 -0
  71. package/public/skins/kita/sticker-live.png +0 -0
  72. package/public/skins/nijika/SOURCES.json +51 -0
  73. package/public/skins/nijika/face.png +0 -0
  74. package/public/skins/nijika/icon-live.png +0 -0
  75. package/public/skins/nijika/icon-reddress.png +0 -0
  76. package/public/skins/nijika/icon-seifuku.png +0 -0
  77. package/public/skins/nijika/pattern.png +0 -0
  78. package/public/skins/nijika/preview.html +56 -0
  79. package/public/skins/nijika/skin.css +25 -0
  80. package/public/skins/nijika/stand.png +0 -0
  81. package/public/skins/nijika/sticker-live.png +0 -0
  82. package/public/skins/penguin/DESIGN.md +33 -0
  83. package/public/skins/penguin/SOURCES.json +22 -0
  84. package/public/skins/penguin/aic-blueprint.svg +24 -0
  85. package/public/skins/penguin/endfield-triangles.svg +4 -0
  86. package/public/skins/penguin/face.png +0 -0
  87. package/public/skins/penguin/icon-blush.png +0 -0
  88. package/public/skins/penguin/icon-dizzy.png +0 -0
  89. package/public/skins/penguin/icon-laugh.png +0 -0
  90. package/public/skins/penguin/icon-sleep.png +0 -0
  91. package/public/skins/penguin/icon-smile.png +0 -0
  92. package/public/skins/penguin/icon-star.png +0 -0
  93. package/public/skins/penguin/icon-wink.png +0 -0
  94. package/public/skins/penguin/icon.png +0 -0
  95. package/public/skins/penguin/mascot.png +0 -0
  96. package/public/skins/penguin/pattern-night.png +0 -0
  97. package/public/skins/penguin/pattern.png +0 -0
  98. package/public/skins/penguin/preview.html +12 -0
  99. package/public/skins/penguin/skin.css +212 -0
  100. package/public/skins/ryo/SOURCES.json +51 -0
  101. package/public/skins/ryo/face.png +0 -0
  102. package/public/skins/ryo/icon-live.png +0 -0
  103. package/public/skins/ryo/icon-reddress.png +0 -0
  104. package/public/skins/ryo/icon-seifuku.png +0 -0
  105. package/public/skins/ryo/pattern.png +0 -0
  106. package/public/skins/ryo/preview.html +56 -0
  107. package/public/skins/ryo/skin.css +25 -0
  108. package/public/skins/ryo/stand.png +0 -0
  109. package/public/skins/ryo/sticker-live.png +0 -0
  110. package/public/sponsor-entry.js +21 -0
  111. package/public/styles.css +29 -19
  112. package/public/teams.js +2 -2
  113. package/public/theme-picker.css +58 -0
  114. package/public/theme-vars.css +532 -5
  115. package/public/theme.js +111 -3
  116. package/public/update.json +12 -12
  117. package/public/version.json +1 -1
  118. package/public/workflow.css +2 -1
  119. package/public/workflow.js +27 -5
  120. package/skills/dsh-remote-doctor/references/wiki/plugins.md +1 -1
  121. package/task-board.mjs +2 -2
  122. package/teams.mjs +7 -2
package/index.mjs CHANGED
@@ -16,6 +16,7 @@ import { fileURLToPath } from 'node:url'
16
16
  import { randomUUID } from 'node:crypto'
17
17
  import { createPluginCenter, detectProfile } from './plugin-center.mjs'
18
18
  import { readCostInsights } from './insights.mjs'
19
+ import { readApprovalSummary } from './approval-summary.mjs'
19
20
  import { readTeamInsights } from './teams.mjs'
20
21
  import { readTaskBoard } from './task-board.mjs'
21
22
  import { readPeakReminders } from './peak-reminders.mjs'
@@ -1296,6 +1297,17 @@ async function serveStatic(req, res, ctx) {
1296
1297
  res.setHeader('cache-control', 'no-store')
1297
1298
  return sendJson(res, result.status, result.body)
1298
1299
  }
1300
+ if (pathname === `${MOUNT}/api/approval-summary`) {
1301
+ res.setHeader('cache-control', 'no-store')
1302
+ if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, code: 'unauthorized' })
1303
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, code: 'method-not-allowed' })
1304
+ if ([...new URL(req.url, 'http://x').searchParams].length) return sendJson(res, 400, { ok: false, code: 'invalid-query' })
1305
+ let body
1306
+ try { body = JSON.parse(await readBody(req, 4096)) }
1307
+ catch { return sendJson(res, 400, { ok: false, code: 'invalid-body' }) }
1308
+ const result = await readApprovalSummary(ctx, body)
1309
+ return sendJson(res, result.status, result.body)
1310
+ }
1299
1311
  if (pathname.startsWith(`${MOUNT}/api/plugins/`)) {
1300
1312
  res.setHeader('cache-control', 'no-store')
1301
1313
  if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, message: 'unauthorized' })
package/insights.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // Read-only, bounded adapter for dsh-cost-meter 1.8.x. Never forward its config.
1
+ // Read-only, bounded adapter for dsh-cost-meter 1.8.x/1.9.x. Never forward its config.
2
2
  const states = new WeakMap()
3
3
  const record = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {}
4
4
  const number = value => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null
@@ -98,9 +98,11 @@ export async function readCostInsights(ctx, sessionId = '') {
98
98
  cache.value = value; cache.at = Date.now(); return value
99
99
  }).finally(() => { cache.task = null })
100
100
  }
101
- const raw = cache.task ? await cache.task : cache.value
102
- const session = sessionId && typeof service.getSessionCost === 'function'
103
- ? await bounded(Promise.resolve().then(() => service.getSessionCost(sessionId))) : null
101
+ // Independent reads share one wait window; serial 20s waits can exceed both
102
+ // the gateway's 30s and the insights client's 25s request budgets.
103
+ const [raw, session] = await Promise.all([cache.task || cache.value,
104
+ sessionId && typeof service.getSessionCost === 'function'
105
+ ? bounded(Promise.resolve().then(() => service.getSessionCost(sessionId))) : null])
104
106
  return { status: 200, body: { ok: true, ...summarizeCost(raw, session, sessionId) } }
105
107
  } catch {
106
108
  // Plugin failures may mention credentials, URLs or paths. Return a fixed code.
package/market.mjs CHANGED
@@ -42,13 +42,16 @@ export function createMarketAdapter(ctx, { timeoutMs = 20000 } = {}) {
42
42
  async function search(url, query) {
43
43
  const empty = { ok: true, available: false, source: 'official', items: [], total: 0, nextOffset: null }
44
44
  if (!validQuery(query)) return { ...empty, ok: false, code: 'invalid-query' }
45
+ const deadline = Date.now() + timeoutMs
45
46
  const state = await indexes()
46
47
  if (!state.available) return { ...empty, code: state.code }
47
48
  const index = url ? state.indexes.find(row => row.url === url) : state.indexes.find(row => !row.code)
48
49
  if (!index) return { ...empty, code: state.indexes.length ? 'unknown-index' : 'no-indexes' }
49
50
  if (index.code) return { ...empty, code: 'index-unavailable' }
50
51
  try {
51
- const result = await bounded(Promise.resolve().then(() => service().search(index.url, query)), timeoutMs)
52
+ const remaining = deadline - Date.now()
53
+ if (remaining <= 0) return { ...empty, code: 'market-unavailable' }
54
+ const result = await bounded(Promise.resolve().then(() => service().search(index.url, query)), remaining)
52
55
  if (!Array.isArray(result.entries)) throw Error('invalid response')
53
56
  const categories = Object.entries(result.metadata?.categories || {}).slice(0, 100).map(([id, row]) => ({ id: text(id, 100), title: localized(row.title) }))
54
57
  const items = result.entries.slice(0, query.limit).filter(row => packageName.test(row.name)).map(row => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-remote-plugin",
3
- "version": "0.8.2",
3
+ "version": "0.8.4",
4
4
  "description": "DSH Remote 官方 bundle 插件:更多菜单中的手机连接入口、首次连接提示与浏览器管理控制台;内置网关自动启停,支持手机远程会话、审批、文件互传和设备管理。",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
@@ -23,6 +23,7 @@
23
23
  "plugin-transaction.mjs",
24
24
  "market.mjs",
25
25
  "insights.mjs",
26
+ "approval-summary.mjs",
26
27
  "teams.mjs",
27
28
  "task-board.mjs",
28
29
  "peak-reminders.mjs",
package/plugin-center.mjs CHANGED
@@ -4,7 +4,7 @@ import { dirname, basename, join, resolve } from 'node:path'
4
4
  import { fileURLToPath } from 'node:url'
5
5
  import { createHash } from 'node:crypto'
6
6
  import { spawn, execFile } from 'node:child_process'
7
- import { prepareReleasePlan, profileRevision, backupTransaction, writeWorkspace, mergeReleaseRules, releasePolicy, verifyInstalled, treeDigest, restoreTransaction, canonicalPath } from './plugin-transaction.mjs'
7
+ import { prepareReleasePlan, profileRevision, backupTransaction, writeWorkspace, mergeReleaseRules, releasePolicy, verifyInstalled, treeDigest, restoreTransaction, canonicalPath, replaceFile } from './plugin-transaction.mjs'
8
8
  import { createMarketAdapter, createReadmeReader } from './market.mjs'
9
9
 
10
10
  const REGISTRY = 'https://registry.npmjs.org'
@@ -16,11 +16,42 @@ const read = path => JSON.parse(readFileSync(path, 'utf8'))
16
16
  function atomic(path, value) {
17
17
  const tmp = path + '.' + process.pid + '.tmp'
18
18
  writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 })
19
- renameSync(tmp, path)
19
+ replaceFile(tmp, path)
20
20
  }
21
21
  const fail = (message, status = 400) => Object.assign(new Error(message), { status })
22
22
  const protectedPackage = name => name === 'dsh-remote-plugin' || name.startsWith('@deepseek-ai/')
23
23
  const revision = path => createHash('sha256').update(readFileSync(path)).digest('hex')
24
+ const registryDependency = value => typeof value === 'string' && !/[:/\\]/.test(value) && !value.startsWith('.')
25
+ function newerVersion(next, previous) {
26
+ const parse = value => /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\w-]+(?:\.[\w-]+)*))?(?:\+[\w.-]+)?$/.exec(value || '')
27
+ const a = parse(next), b = parse(previous)
28
+ if (!a || !b || [a, b].some(parts => parts[4]?.split('.').some(v => /^0\d+$/.test(v)))) return false
29
+ const numeric = (x, y) => x.length !== y.length ? Math.sign(x.length - y.length) : x === y ? 0 : x < y ? -1 : 1
30
+ for (let i = 1; i <= 3; i++) { const order = numeric(a[i], b[i]); if (order) return order > 0 }
31
+ if (!a[4] || !b[4]) return !a[4] && !!b[4]
32
+ const x = a[4].split('.'), y = b[4].split('.')
33
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
34
+ if (x[i] === y[i]) continue
35
+ if (x[i] === undefined || y[i] === undefined) return y[i] === undefined
36
+ const nx = /^\d+$/.test(x[i]), ny = /^\d+$/.test(y[i])
37
+ return (nx && ny ? numeric(x[i], y[i]) : nx !== ny ? nx ? -1 : 1 : x[i] < y[i] ? -1 : 1) > 0
38
+ }
39
+ return false
40
+ }
41
+ function batchTargets(body, state) {
42
+ if (body.name !== 'all-plugins' || !Array.isArray(body.targets) || !body.targets.length || body.targets.length > 100) throw fail('无效的批量更新列表')
43
+ const names = new Set()
44
+ const targets = body.targets.map(target => {
45
+ if (!target || !packagePattern.test(target.name || '') || !versionPattern.test(target.version || '') || names.has(target.name)) throw fail('无效或重复的批量更新目标')
46
+ names.add(target.name)
47
+ const item = state.items.find(item => item.name === target.name)
48
+ if (!item || !(item.managed && item.bundle || item.selfUpdate) || !registryDependency(item.requested)) throw fail('批量更新只接受当前 profile 的 registry 插件:' + target.name, 409)
49
+ if (!newerVersion(target.version, item.version)) throw fail('批量更新不能重装、降级或替换未知版本:' + target.name, 409)
50
+ return { name: target.name, version: target.version, fromVersion: item.version, enabled: item.enabled }
51
+ })
52
+ return targets.sort((a, b) => (a.name === 'dsh-remote-plugin') - (b.name === 'dsh-remote-plugin') || a.name.localeCompare(b.name))
53
+ }
54
+ const targetIdentity = targets => JSON.stringify((Array.isArray(targets) ? targets : []).map(target => ({ name: target?.name, version: target?.version })).sort((a, b) => String(a.name).localeCompare(String(b.name))))
24
55
  function adapterInterfaces(ctx) {
25
56
  // Shape checks only: never query balances, read content or activate sessions.
26
57
  const result = {}
@@ -174,12 +205,12 @@ export function detectProfile(ctx, cli = process.argv[1], runtime = process) {
174
205
 
175
206
  async function registryJson(path, signal = AbortSignal.timeout(20000)) {
176
207
  const response = await fetch(REGISTRY + path, { signal, redirect: 'error' })
177
- if (!response.ok) throw fail('npm registry: HTTP ' + response.status, 502)
208
+ if (!response.ok) { await response.body?.cancel(); throw fail('npm registry ' + path + ': HTTP ' + response.status, 502) }
178
209
  let raw = '', bytes = 0
179
210
  const decoder = new TextDecoder()
180
211
  for await (const chunk of response.body) {
181
212
  bytes += chunk.length
182
- if (bytes > 8 * 1024 * 1024) throw fail('Registry response too large', 502)
213
+ if (bytes > 8 * 1024 * 1024) throw fail('Registry response too large: ' + path + ' (' + bytes + ' bytes; limit ' + 8 * 1024 * 1024 + ')', 502)
183
214
  raw += decoder.decode(chunk, { stream: true })
184
215
  }
185
216
  raw += decoder.decode()
@@ -201,18 +232,131 @@ export async function pluginDetails(name, version = 'latest') {
201
232
  }
202
233
 
203
234
  const publicationCache = new Map()
204
- async function publicationTimes(name, signal) {
235
+ // Validate full package JSON without accumulating all-version manifests. Only
236
+ // requested string/string-map fields are retained; unrelated content is skipped.
237
+ function registryProjection(fields) {
238
+ const stack = [], result = Object.create(null)
239
+ let root = false, done = false, token = '', mode = '', escaped = false, unicode = 0, capture = false, retained = 0
240
+ let prefixLimit = Infinity, decodedChars = 0, truncatedString = false
241
+ const invalid = () => { throw fail('Invalid npm publication metadata', 502) }
242
+ const wanted = frame => frame.keep || stack.length === 1 && Object.hasOwn(fields, frame.key)
243
+ function accept(kind, value) {
244
+ const frame = stack.at(-1)
245
+ if (kind === '}' || kind === ']') {
246
+ if (!frame || frame.kind !== (kind === '}' ? '{' : '[') || !['first', 'end'].includes(frame.state)) invalid()
247
+ stack.pop(); if (!stack.length) done = true
248
+ return
249
+ }
250
+ if (kind === ':') { if (frame?.state !== 'colon') invalid(); frame.state = 'value'; return }
251
+ if (kind === ',') { if (frame?.state !== 'end') invalid(); frame.state = frame.kind === '{' ? 'key' : 'value'; return }
252
+ if (frame?.kind === '{' && ['first', 'key'].includes(frame.state)) {
253
+ if (kind !== 'string') invalid()
254
+ frame.key = value; frame.state = 'colon'; return
255
+ }
256
+ if (frame && !(frame.state === 'value' || frame.kind === '[' && frame.state === 'first')) invalid()
257
+ if (!frame && (root || kind !== '{')) invalid()
258
+ const keep = frame ? wanted(frame) : false
259
+ if (keep && (stack.length === 1 && fields[frame.key] === 'map' ? kind !== '{' : kind !== 'string')) invalid()
260
+ const container = kind === '{' || kind === '['
261
+ const next = container ? kind === '{' ? Object.create(null) : [] : value
262
+ if (!frame) root = true
263
+ else {
264
+ if (keep) {
265
+ const target = stack.length === 1 ? result : frame.value
266
+ if (frame.kind === '[') target.push(next)
267
+ else { if (Object.hasOwn(target, frame.key)) invalid(); target[frame.key] = next }
268
+ }
269
+ frame.state = 'end'
270
+ }
271
+ if (container) {
272
+ if (stack.length >= 64) invalid()
273
+ stack.push({ kind, state: 'first', keep, value: next, key: '' })
274
+ }
275
+ }
276
+ function append(char) {
277
+ if (capture) {
278
+ if (++retained > 1024 * 1024) throw fail('npm publication fields exceed 1048576 characters', 502)
279
+ token += char
280
+ }
281
+ }
282
+ function stringUnit() {
283
+ // Stop at a complete decoded UTF-16 unit, never in a JSON escape. Keep one
284
+ // extra character so the existing README adapter reports truncation.
285
+ if (capture && ++decodedChars >= prefixLimit) { capture = false; truncatedString = true }
286
+ }
287
+ function push(raw) {
288
+ for (let i = 0; i < raw.length; i++) {
289
+ const char = raw[i]
290
+ if (mode === 'string') {
291
+ append(char)
292
+ if (unicode) { if (!/[a-fA-F0-9]/.test(char)) invalid(); unicode--; if (!unicode) stringUnit(); continue }
293
+ if (escaped) { if (char === 'u') unicode = 4; else if (!'"\\/bfnrt'.includes(char)) invalid(); escaped = false; if (char !== 'u') stringUnit(); continue }
294
+ if (char === '\\') { escaped = true; continue }
295
+ if (char === '"') { accept('string', capture ? JSON.parse(token) : truncatedString ? JSON.parse(token + '"') : undefined); mode = ''; token = ''; continue }
296
+ if (char.charCodeAt(0) < 32) invalid()
297
+ stringUnit()
298
+ continue
299
+ }
300
+ if (mode === 'scalar') {
301
+ if (!/[\s,}\]]/.test(char)) { if (token.length >= 128) invalid(); token += char; continue }
302
+ if (!/^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)$/.test(token)) invalid()
303
+ accept('scalar', JSON.parse(token)); mode = ''; token = ''; i--; continue
304
+ }
305
+ if (/^[ \r\n\t]$/.test(char)) continue
306
+ if (done) invalid()
307
+ if ('{}[]:,'.includes(char)) { accept(char); continue }
308
+ if (char === '"') {
309
+ const frame = stack.at(-1)
310
+ capture = !!frame && (frame.kind === '{' && ['first', 'key'].includes(frame.state) ? frame.keep || stack.length === 1 : wanted(frame))
311
+ prefixLimit = stack.length === 1 && frame?.state === 'value' && frame.key === 'readme' ? 100001 : Infinity
312
+ decodedChars = 0; truncatedString = false
313
+ token = ''; mode = 'string'; append(char); continue
314
+ }
315
+ if (!/[tfn\d-]/.test(char)) invalid()
316
+ token = char; mode = 'scalar'
317
+ }
318
+ }
319
+ return { push, finish() { if (!done || mode || stack.length) invalid(); return result } }
320
+ }
321
+ async function registryMetadata(name, signal, fields) {
322
+ if (!packagePattern.test(name)) throw fail('Invalid package')
323
+ const requestSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(20000)]) : AbortSignal.timeout(20000)
324
+ let data, bytes = 0
325
+ try {
326
+ const response = await fetch(REGISTRY + '/' + encodeURIComponent(name), { signal: requestSignal, redirect: 'error', headers: { accept: 'application/json' } })
327
+ if (!response.ok) { await response.body?.cancel(); throw fail('HTTP ' + response.status, 502) }
328
+ const projection = registryProjection(fields), decoder = new TextDecoder('utf-8', { fatal: true })
329
+ for await (const chunk of response.body) {
330
+ bytes += chunk.length
331
+ if (bytes > 64 * 1024 * 1024) throw fail('Registry response too large (' + bytes + ' bytes; limit 67108864)', 502)
332
+ projection.push(decoder.decode(chunk, { stream: true }))
333
+ }
334
+ projection.push(decoder.decode()); data = projection.finish()
335
+ if (data.name !== name) throw fail('Invalid npm package identity', 502)
336
+ } catch (error) {
337
+ const reason = requestSignal.aborted ? 'npm 元数据读取超时或已取消' : error.status ? error.message : 'Registry response failed or invalid'
338
+ throw fail('npm ' + name + ': ' + reason + ' (received ' + bytes + ' bytes)', 502)
339
+ }
340
+ return data
341
+ }
342
+ // install-v1 metadata omits `time`; keep full-format publication evidence.
343
+ export async function publicationTimes(name, signal, versions = []) {
344
+ if (!packagePattern.test(name)) throw fail('Invalid package')
205
345
  const cached = publicationCache.get(name)
206
- if (cached?.until > Date.now()) return cached.value
207
- const data = await registryJson('/' + encodeURIComponent(name), signal)
208
- if (data.name !== name || !data.time || typeof data.time !== 'object') throw fail('npm 未提供可核验的发布时间:' + name, 502)
346
+ if (cached?.until > Date.now() && versions.every(version => Object.hasOwn(cached.value, version))) return cached.value
347
+ const data = await registryMetadata(name, signal, { name: 'string', time: 'map' })
348
+ if (!data.time) throw fail('npm ' + name + ': npm 未提供可核验的发布时间', 502)
209
349
  publicationCache.set(name, { value: data.time, until: Date.now() + 5 * 60000 })
210
350
  if (publicationCache.size > 1500) publicationCache.delete(publicationCache.keys().next().value)
211
351
  return data.time
212
352
  }
353
+ async function readmeRegistryJson(path, signal) {
354
+ const name = decodeURIComponent(path.slice(1))
355
+ return registryMetadata(name, signal, { name: 'string', readme: 'string', 'dist-tags': 'map' })
356
+ }
213
357
 
214
358
  export function createPluginCenter(ctx, options = {}) {
215
- const market = createMarketAdapter(ctx), readme = createReadmeReader(options.registryJson || registryJson)
359
+ const market = createMarketAdapter(ctx), readme = createReadmeReader(options.registryJson || readmeRegistryJson)
216
360
  const profile = options.profile === undefined ? detectProfile(ctx) : options.profile
217
361
  const details = options.details || pluginDetails
218
362
  const probe = options.probeProcesses || probeProcesses
@@ -249,11 +393,17 @@ export function createPluginCenter(ctx, options = {}) {
249
393
  let submitting = false
250
394
  async function preflight(body) {
251
395
  if (!profile?.cli) throw fail('当前环境只读', 409)
252
- if (!body || !['install', 'update', 'remove'].includes(body.action) || !packagePattern.test(body.name || '') || (body.action !== 'remove' && !versionPattern.test(body.version || ''))) throw fail('Invalid operation')
396
+ if (!body || !['install', 'update', 'remove', 'update-all'].includes(body.action) || !packagePattern.test(body.name || '') || (!['remove', 'update-all'].includes(body.action) && !versionPattern.test(body.version || ''))) throw fail('Invalid operation')
253
397
  if (protectedPackage(body.name) && !(body.action === 'update' && body.name === 'dsh-remote-plugin')) throw fail('核心插件请通过主机维护流程管理', 409)
254
398
  if (body.revision !== revision(manifestPath)) throw fail('插件列表已变化,请刷新', 409)
255
399
  const state = await inventory()
256
400
  if (state.busy || state.profileLock && state.profileLock.state !== 'dead') throw fail('已有插件任务或配置锁,请等待后重试', 409)
401
+ if (body.action === 'update-all') {
402
+ body = { ...body, targets: batchTargets(body, state) }
403
+ for (let i = 0; i < body.targets.length; i += 6) await Promise.all(body.targets.slice(i, i + 6).map(async target => {
404
+ if (!(await details(target.name, target.version)).bundle) throw fail('该版本未声明 DSH bundle:' + target.name)
405
+ }))
406
+ }
257
407
  const plan = await prepareReleasePlan(profile.dir, body, options.publicationTimes || publicationTimes)
258
408
  const key = createHash('sha256').update(JSON.stringify(plan) + Math.random()).digest('hex')
259
409
  mkdirSync(storage, { recursive: true, mode: 0o700 })
@@ -305,7 +455,7 @@ export function createPluginCenter(ctx, options = {}) {
305
455
  busy: submitting || !!owner, busyReason: owner ? busyReason || '主机任务正在启动;可查看操作记录。' : '',
306
456
  profileLock: await profileLock(profile.dir, probe).then(lock => lock && ({ state: lock.state, message: lock.message })),
307
457
  recovery: legacyLock ? { id: owner.id, reason: '旧任务锁没有进程信息,需在主机核对后手动解除。' } : null,
308
- capabilities: { preflight: true, restore: true }, items, runtime, runtimeAvailable, operations }
458
+ capabilities: { preflight: true, restore: true, updateAll: true }, items, runtime, runtimeAvailable, operations }
309
459
  }
310
460
  function recoverLegacy(body) {
311
461
  if (!profile?.cli || submitting) throw fail('当前不能恢复任务', 409)
@@ -331,7 +481,7 @@ export function createPluginCenter(ctx, options = {}) {
331
481
  if (!profile?.cli) throw fail('Current DSH profile is read-only', 409)
332
482
  if (!body || typeof body !== 'object' || Array.isArray(body)) throw fail('Invalid operation')
333
483
  const { id, action, name, version } = body
334
- if (!idPattern.test(id || '') || !packagePattern.test(name || '') || !['install', 'update', 'remove', 'enable', 'disable', 'restore'].includes(action)) throw fail('Invalid operation')
484
+ if (!idPattern.test(id || '') || !packagePattern.test(name || '') || !['install', 'update', 'update-all', 'remove', 'enable', 'disable', 'restore'].includes(action)) throw fail('Invalid operation')
335
485
  const selfUpdate = name === 'dsh-remote-plugin' && action === 'update'
336
486
  if (protectedPackage(name) && !selfUpdate && action !== 'restore') throw fail('核心插件与 Remote 的卸载、启停请通过主机维护流程管理', 409)
337
487
  if (selfUpdate && body.confirmSelfUpdate !== true) throw fail('请确认 Remote 本体更新及重启后生效', 409)
@@ -340,7 +490,7 @@ export function createPluginCenter(ctx, options = {}) {
340
490
  const jobPath = join(storage, 'job-' + id + '.json')
341
491
  if (existsSync(jobPath)) {
342
492
  const previous = read(jobPath)
343
- if (previous.action !== action || previous.name !== name || previous.version !== (version || '') || (previous.restoreFrom || '') !== (body.restoreFrom || '') || (previous.planKey || '') !== (body.preflightKey || '')) throw fail('Operation id already used', 409)
493
+ if (previous.action !== action || previous.name !== name || previous.version !== (version || '') || (previous.restoreFrom || '') !== (body.restoreFrom || '') || (previous.planKey || '') !== (body.preflightKey || '') || action === 'update-all' && targetIdentity(previous.targets) !== targetIdentity(body.targets)) throw fail('Operation id already used', 409)
344
494
  return publicJob(previous)
345
495
  }
346
496
  if (submitting) throw fail('另一个插件操作正在准备中', 409)
@@ -349,7 +499,7 @@ export function createPluginCenter(ctx, options = {}) {
349
499
  if (revision(manifestPath) !== body.revision) throw fail('插件列表已变化,请刷新后重试', 409)
350
500
  const manifest = read(manifestPath)
351
501
  const installed = Object.hasOwn(manifest.dependencies || {}, name)
352
- if (action !== 'restore' && (action === 'install' && installed || action !== 'install' && !installed)) throw fail('安装状态已变化,请刷新', 409)
502
+ if (!['restore', 'update-all'].includes(action) && (action === 'install' && installed || action !== 'install' && !installed)) throw fail('安装状态已变化,请刷新', 409)
353
503
  let plan = null, restoreFrom = null
354
504
  if (body.preflightKey) {
355
505
  if (!/^[a-f0-9]{64}$/.test(body.preflightKey)) throw fail('无效的预检凭据')
@@ -359,6 +509,11 @@ export function createPluginCenter(ctx, options = {}) {
359
509
  if (plan.action !== action || plan.name !== name || plan.version !== (version || '') || plan.expiresAt < Date.now() || plan.revision !== profileRevision(profile.dir)) throw fail('预检已过期或配置已变化,请重新预检', 409)
360
510
  if ((plan.blockers.length || plan.ruleChanges.length) && body.confirmReleasePolicy !== true) throw fail('请明确批准预检中列出的精确版本豁免及重复规则合并', 409)
361
511
  }
512
+ if (action === 'update-all') {
513
+ if (!plan || targetIdentity(plan.targets) !== targetIdentity(body.targets)) throw fail('批量更新必须使用已确认的完整预检列表', 409)
514
+ batchTargets(body, await inventory())
515
+ if (plan.targets.some(target => target.name === 'dsh-remote-plugin') && body.confirmSelfUpdate !== true) throw fail('请确认批量更新包含 Remote 本体', 409)
516
+ }
362
517
  if (action === 'restore') {
363
518
  if (!idPattern.test(body.restoreFrom || '') || body.confirmRestore !== true) throw fail('请确认恢复失败前的插件和配置', 409)
364
519
  const source = read(join(storage, 'job-' + body.restoreFrom + '.json'))
@@ -380,6 +535,7 @@ export function createPluginCenter(ctx, options = {}) {
380
535
  try { writeFileSync(lock, JSON.stringify({ id, launcherPid: process.pid, createdAt: Date.now() }), { flag: 'wx', mode: 0o600 }) }
381
536
  catch (error) { if (error.code === 'EEXIST') throw fail('已有插件任务运行中;请查看操作记录', 409); throw error }
382
537
  const job = { id, action, name, version: version || '', revision: body.revision, profile: profile.name, phase: 'queued', stage: 'queued', startedAt: Date.now(), updatedAt: Date.now(), log: '', restartRequired: false,
538
+ ...(action === 'update-all' ? { targets: plan.targets.map(target => ({ ...target, phase: 'queued' })) } : {}),
383
539
  ...(plan ? { plan, planKey: body.preflightKey } : {}), ...(restoreFrom ? { restoreFrom } : {}) }
384
540
  try {
385
541
  atomic(jobPath, job)
@@ -409,7 +565,7 @@ export function createPluginCenter(ctx, options = {}) {
409
565
  ...(query.get('refresh') === '1' ? { refresh: true } : {}) })
410
566
  }
411
567
  if (method === 'POST' && sub === '/operations') {
412
- if (['install', 'update', 'remove'].includes(body.action) && !body.preflightKey) throw fail('请先预检并确认更新计划;旧版客户端需升级 Remote 页面', 409)
568
+ if (['install', 'update', 'update-all', 'remove'].includes(body.action) && !body.preflightKey) throw fail('请先预检并确认更新计划;旧版客户端需升级 Remote 页面', 409)
413
569
  return { ok: true, operation: await submit(body) }
414
570
  }
415
571
  if (method === 'POST' && sub === '/preflight') return preflight(body)
@@ -422,6 +578,7 @@ export function createPluginCenter(ctx, options = {}) {
422
578
  function publicJob(job) {
423
579
  const { id, action, name, version, profile, phase, stage, startedAt, endedAt, updatedAt, lastOutputAt, log, message, restartRequired } = job
424
580
  return { id, action, name, version, profile, phase, stage, startedAt, endedAt, updatedAt, lastOutputAt, log, message, restartRequired,
581
+ ...(job.targets ? { targets: job.targets.map(({ name, version, fromVersion, phase, message }) => ({ name, version, fromVersion, phase, message })) } : {}),
425
582
  canRestore: !!job.recoveryState && !job.restoredBy && ['failed', 'interrupted'].includes(phase), restoredBy: job.restoredBy || '' }
426
583
  }
427
584
 
@@ -474,6 +631,7 @@ export async function runWorker(dir, cli, id, execute = runCli, cliMode = 'node'
474
631
  heartbeat = setInterval(save, 4000); heartbeat.unref()
475
632
  if (job.revision !== revision(manifestPath)) throw fail('任务开始前 profile 已变化,请刷新后重试')
476
633
  disabled = new Set(existsSync(disabledPath) ? read(disabledPath) : [])
634
+ if (job.action === 'update-all') for (const target of job.targets) if (!target.enabled) disabled.add(target.name)
477
635
  const backup = join(storage, 'backup-' + id)
478
636
  mkdirSync(backup, { mode: 0o700 })
479
637
  for (const name of ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'cordis.patch.yml', 'cordis.yml', '.npmrc']) {
@@ -511,14 +669,32 @@ export async function runWorker(dir, cli, id, execute = runCli, cliMode = 'node'
511
669
  writeWorkspace(dir, job.plan.workspace)
512
670
  })
513
671
  }
514
- if (['install', 'update', 'remove'].includes(job.action)) {
672
+ if (['install', 'update', 'remove', 'update-all'].includes(job.action)) {
515
673
  progress('cli', '正在运行 DSH 插件命令,等待主机输出。')
516
- const args = job.action === 'remove' ? ['remove', job.name, '--config.ignore-scripts=true'] : ['add', job.name + '@' + job.version, '--save-exact', '--ignore-scripts', '--registry=' + REGISTRY]
517
- await execute(cli, ['plugin', '--profile', basename(dir), ...args], dir, chunk => {
518
- job.lastOutputAt = Date.now()
519
- job.log = (job.log + chunk.replace(/\x1b\[[0-9;]*m/g, '').replace(/(token|password|authorization)\s*[=:]\s*\S+/gi, '$1=[redacted]')).slice(-12000)
520
- save()
521
- }, pid => atomic(lock, { ...read(lock), cliPid: pid }), cliMode)
674
+ const targets = job.action === 'update-all' ? job.targets : [job]
675
+ let batchRevision = job.action === 'update-all' ? profileRevision(dir) : null
676
+ for (const target of targets) {
677
+ if (job.action === 'update-all') {
678
+ if (profileRevision(dir) !== batchRevision) throw fail('批量更新期间主机配置已被其他操作改变,已停止后续项。')
679
+ target.phase = 'running'; progress('cli', '正在更新 ' + target.name + '@' + target.version + '(' + (targets.indexOf(target) + 1) + '/' + targets.length + ')。')
680
+ }
681
+ const args = job.action === 'remove' ? ['remove', target.name, '--config.ignore-scripts=true'] : ['add', target.name + '@' + target.version, '--save-exact', '--ignore-scripts', '--registry=' + REGISTRY]
682
+ await execute(cli, ['plugin', '--profile', basename(dir), ...args], dir, chunk => {
683
+ job.lastOutputAt = Date.now()
684
+ job.log = (job.log + chunk.replace(/\x1b\[[0-9;]*m/g, '').replace(/(token|password|authorization)\s*[=:]\s*\S+/gi, '$1=[redacted]')).slice(-12000)
685
+ save()
686
+ }, pid => atomic(lock, { ...read(lock), cliPid: pid }), cliMode)
687
+ if (job.action === 'update-all') await guarded(() => {
688
+ const manifest = read(manifestPath)
689
+ manifest.dsh.profile.bundles = manifest.dsh.profile.bundles.filter(name => !disabled.has(name))
690
+ atomic(manifestPath, manifest); atomic(disabledPath, [...disabled])
691
+ const pkg = read(join(dir, 'node_modules', ...target.name.split('/'), 'package.json'))
692
+ if (pkg.version !== target.version || !pkg.dsh?.bundle?.patch || manifest.dependencies?.[target.name] !== target.version) throw fail('安装后的包版本、精确依赖或 bundle 校验失败:' + target.name)
693
+ verifyInstalled(dir, job)
694
+ batchRevision = profileRevision(dir)
695
+ target.phase = 'complete'; save()
696
+ })
697
+ }
522
698
  }
523
699
  const verify = () => {
524
700
  progress('verify', '正在保存配置并核验插件状态。')
@@ -530,7 +706,11 @@ export async function runWorker(dir, cli, id, execute = runCli, cliMode = 'node'
530
706
  atomic(manifestPath, manifest)
531
707
  atomic(disabledPath, [...disabled])
532
708
  const installed = Object.hasOwn(manifest.dependencies || {}, job.name)
533
- if (job.action === 'remove' ? installed : !installed) throw fail('操作后依赖状态与预期不符')
709
+ if (job.action !== 'update-all' && (job.action === 'remove' ? installed : !installed)) throw fail('操作后依赖状态与预期不符')
710
+ if (job.action === 'update-all') for (const target of job.targets) {
711
+ const pkg = read(join(dir, 'node_modules', ...target.name.split('/'), 'package.json'))
712
+ if (pkg.version !== target.version || manifest.dependencies?.[target.name] !== target.version) throw fail('批量更新最终版本不一致:' + target.name)
713
+ }
534
714
  if (['install', 'update'].includes(job.action)) {
535
715
  const pkg = read(join(dir, 'node_modules', ...job.name.split('/'), 'package.json'))
536
716
  if (pkg.version !== job.version || !pkg.dsh?.bundle?.patch) throw fail('安装后的包版本或 bundle 校验失败')
@@ -551,7 +731,11 @@ export async function runWorker(dir, cli, id, execute = runCli, cliMode = 'node'
551
731
  job.message = '配置已保存;重启 DSH 后生效。安装脚本未执行。'
552
732
  } catch (error) {
553
733
  job.phase = 'failed'; job.message = String(error.message || error)
554
- if(job.name==='dsh-remote-plugin' && /(?:ERR_PNPM_)?(?:EPERM|EBUSY)/.test(job.log) && /rename/i.test(job.log)) {
734
+ if (job.action === 'update-all') for (const target of job.targets) {
735
+ if (target.phase === 'running') { target.phase = 'failed'; target.message = job.message }
736
+ else if (target.phase === 'queued') { target.phase = 'interrupted'; target.message = '前项失败,未执行;请先核对或恢复本次备份。' }
737
+ }
738
+ if((job.name==='dsh-remote-plugin' || job.targets?.some(target => target.name === 'dsh-remote-plugin' && target.phase === 'failed')) && /(?:ERR_PNPM_)?(?:EPERM|EBUSY)/.test(job.log) && /rename/i.test(job.log)) {
555
739
  job.message = 'Windows 拒绝替换 Remote 插件目录,可能仍有旧网关或 DSH 进程占用。更新未完成,配置和旧包备份已保留;请退出对应 DSH Desktop 及其 Remote 网关后,使用同一 Desktop 安装自带的 CLI 在当前 profile 重装目标版本,再启动 DSH。不要删除插件目录或强行覆盖;不能假定失败后已自动回滚。'
556
740
  }
557
741
  const policyNotice = job.message === String(error.message || error) ? immatureReleaseNotice(job.log) : null
@@ -7,6 +7,20 @@ const pkgName = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/
7
7
  const semver = /^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$/
8
8
  export const controlFiles = ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'cordis.patch.yml', 'cordis.yml', '.npmrc', '.remote-plugin-center/disabled.json']
9
9
  const error = message => Object.assign(new Error(message), { status: 409 })
10
+ // Windows can temporarily refuse replacement while a reader holds the target.
11
+ // The manager polls these ledger files, so a short bounded retry is
12
+ // safe: only the metadata rename is repeated, never an install command or any
13
+ // other result-uncertain write.
14
+ const retryCell = new Int32Array(new SharedArrayBuffer(4))
15
+ export function replaceFile(tmp, file) {
16
+ for (let attempt = 0; ; attempt++) {
17
+ try { return renameSync(tmp, file) }
18
+ catch (failure) {
19
+ if (!['EPERM', 'EACCES', 'EBUSY'].includes(failure.code) || attempt >= 20) throw failure
20
+ Atomics.wait(retryCell, 0, 0, 10)
21
+ }
22
+ }
23
+ }
10
24
  const text = file => existsSync(file) ? readFileSync(file, 'utf8') : null
11
25
  const hash = value => createHash('sha256').update(value).digest('hex')
12
26
  export function profileRevision(dir) { return hash(JSON.stringify(controlFiles.map(name => [name, text(join(dir, name))]))) }
@@ -116,10 +130,13 @@ export async function prepareReleasePlan(dir, operation, publishedTimes, env = p
116
130
  const policy = releasePolicy(workspace, env, text(join(dir, '.npmrc')) || '')
117
131
  const packages = lockPackages(text(join(dir, 'pnpm-lock.yaml')))
118
132
  if (operation.version) packages.push({ name: operation.name, version: operation.version })
133
+ if (operation.action === 'update-all') packages.push(...operation.targets.map(({ name, version }) => ({ name, version })))
119
134
  const pairs = [...new Map(packages.map(row => [row.name + '@' + row.version, row])).values()]
120
135
  const blockers = [], now = Date.now(), names = [...new Set(pairs.map(row => row.name))]
121
136
  let cursor = 0
122
- const controller = new AbortController(), timeout = setTimeout(() => controller.abort(), 20000)
137
+ // Give large lockfiles multiple request batches, within the client/proxy budget.
138
+ const budget = Math.min(120000, Math.max(20000, Math.ceil(names.length / 6) * 20000))
139
+ const controller = new AbortController(), timeout = setTimeout(() => controller.abort(), budget)
123
140
  try { if (policy.minutes > 0) await Promise.all(Array.from({ length: Math.min(6, names.length) }, async () => {
124
141
  while (cursor < names.length) {
125
142
  if (controller.signal.aborted) throw error('发布时间预检超时,请重试;不会执行安装。')
@@ -128,19 +145,25 @@ export async function prepareReleasePlan(dir, operation, publishedTimes, env = p
128
145
  const first = policy.entries.find(rule => rule.name === name)
129
146
  const checked = pairs.filter(row => row.name === name && !(first && (!first.versions.length || first.versions.includes(row.version))))
130
147
  if (!checked.length) continue
131
- const times = await publishedTimes(name, controller.signal)
148
+ const times = await publishedTimes(name, controller.signal, checked.map(row => row.version))
132
149
  for (const row of checked) {
133
150
  const at = Date.parse(times[row.version])
134
151
  if (!Number.isFinite(at) || at > now + 60000) throw error('无法核实 ' + name + '@' + row.version + ' 的发布时间,未放行;请稍后重试。')
135
152
  if (at + policy.minutes * 60000 > now) blockers.push({ ...row, publishedAt: new Date(at).toISOString(), eligibleAt: new Date(at + policy.minutes * 60000).toISOString() })
136
153
  }
137
154
  }
138
- })) } catch (failure) { controller.abort(); throw failure } finally { clearTimeout(timeout) }
155
+ })) } catch (failure) {
156
+ const timedOut = controller.signal.aborted
157
+ controller.abort()
158
+ if (timedOut) throw error('发布时间预检超时(' + budget / 1000 + ' 秒,' + names.length + ' 个包),不会执行安装;请重试。')
159
+ throw failure
160
+ } finally { clearTimeout(timeout) }
139
161
  blockers.sort((a, b) => (a.name + '@' + a.version).localeCompare(b.name + '@' + b.version))
140
162
  const merged = mergeReleaseRules(workspace, blockers)
141
163
  if (profileRevision(dir) !== before) throw error('预检期间主机配置已变化,请重新预检。')
142
164
  return { revision: before, minutes: policy.minutes, blockers, ruleChanges: merged.changes, workspace: merged.raw, baselineWarning,
143
- action: operation.action, name: operation.name, version: operation.version || '', expiresAt: Date.now() + 10 * 60000 }
165
+ action: operation.action, name: operation.name, version: operation.version || '',
166
+ ...(operation.action === 'update-all' ? { targets: operation.targets } : {}), expiresAt: Date.now() + 10 * 60000 }
144
167
  }
145
168
  export function canonicalPath(value) {
146
169
  let current = resolve(value)
@@ -209,7 +232,7 @@ export async function backupTransaction(dir, backup) {
209
232
  export function writeWorkspace(dir, raw) {
210
233
  if (raw === null) return
211
234
  const file = join(dir, 'pnpm-workspace.yaml'), tmp = file + '.remote-' + process.pid
212
- writeFileSync(tmp, raw, { mode: 0o600 }); renameSync(tmp, file)
235
+ writeFileSync(tmp, raw, { mode: 0o600 }); replaceFile(tmp, file)
213
236
  }
214
237
  export function verifyInstalled(dir, job) {
215
238
  const manifest = JSON.parse(text(join(dir, 'package.json'))), raw = text(join(dir, 'pnpm-lock.yaml'))
@@ -260,7 +283,7 @@ export async function restoreTransaction(dir, sourceBackup, failed, destination)
260
283
  if (profileRevision(dir) !== failed.revision || treeDigest(current) !== failed.installed) throw error('准备恢复时主机状态发生变化,已停止。')
261
284
  const previousFiles = Object.fromEntries(controlFiles.map(name => [name, text(join(dir, name))]))
262
285
  let moved = false, installed = false
263
- const put = (name, value) => { const file = join(dir, name); if (value === null) { if (existsSync(file)) unlinkSync(file) } else { writeFileSync(file + '.remote-' + process.pid, value, { mode: 0o600 }); renameSync(file + '.remote-' + process.pid, file) } }
286
+ const put = (name, value) => { const file = join(dir, name); if (value === null) { if (existsSync(file)) unlinkSync(file) } else { writeFileSync(file + '.remote-' + process.pid, value, { mode: 0o600 }); replaceFile(file + '.remote-' + process.pid, file) } }
264
287
  try {
265
288
  if (existsSync(current)) { renameSync(current, displaced); moved = true }
266
289
  if (record.installed !== null) { renameSync(staged, current); installed = true }