dsh-coexist-cli 0.0.0-stage → 0.1.0

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.
package/src/backup.js ADDED
@@ -0,0 +1,104 @@
1
+ import fs from 'node:fs/promises'
2
+ import path from 'node:path'
3
+ import { backupsDir } from './paths.js'
4
+
5
+ export async function createBackup(home, files) {
6
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-')
7
+ const dir = path.join(backupsDir(home), stamp)
8
+ await fs.mkdir(dir, { recursive: true })
9
+
10
+ const manifest = {
11
+ createdAt: new Date().toISOString(),
12
+ files: [],
13
+ }
14
+
15
+ for (const file of files) {
16
+ try {
17
+ const content = await fs.readFile(file)
18
+ const rel = path.relative(home, file)
19
+ if (rel.startsWith('..')) {
20
+ throw new Error(`Refusing to back up a file outside DSH_HOME: ${file}`)
21
+ }
22
+ const dest = path.join(dir, rel)
23
+ await fs.mkdir(path.dirname(dest), { recursive: true })
24
+ await fs.writeFile(dest, content)
25
+ manifest.files.push({ file, rel })
26
+ } catch (err) {
27
+ if (err.code !== 'ENOENT') throw err
28
+ }
29
+ }
30
+
31
+ await fs.writeFile(path.join(dir, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`)
32
+ return { dir, manifest }
33
+ }
34
+
35
+ export async function latestBackup(home) {
36
+ let entries
37
+ try {
38
+ entries = await fs.readdir(backupsDir(home), { withFileTypes: true })
39
+ } catch (err) {
40
+ if (err.code === 'ENOENT') return null
41
+ throw err
42
+ }
43
+
44
+ const dirs = entries
45
+ .filter((entry) => entry.isDirectory())
46
+ .map((entry) => entry.name)
47
+ .sort()
48
+
49
+ if (dirs.length === 0) return null
50
+
51
+ const dir = path.join(backupsDir(home), dirs[dirs.length - 1])
52
+ const manifest = JSON.parse(await fs.readFile(path.join(dir, 'manifest.json'), 'utf8'))
53
+ return { dir, manifest }
54
+ }
55
+
56
+ export async function rollback(home) {
57
+ const latest = await latestBackup(home)
58
+ if (!latest) return { restored: [], backup: null }
59
+
60
+ const restored = []
61
+ for (const item of latest.manifest.files) {
62
+ const source = path.join(latest.dir, item.rel)
63
+ await fs.mkdir(path.dirname(item.file), { recursive: true })
64
+ await fs.copyFile(source, item.file)
65
+ restored.push(item.file)
66
+ }
67
+
68
+ return { restored, backup: latest.dir }
69
+ }
70
+
71
+ export async function listBackups(home) {
72
+ let entries
73
+ try {
74
+ entries = await fs.readdir(backupsDir(home), { withFileTypes: true })
75
+ } catch (err) {
76
+ if (err.code === 'ENOENT') return []
77
+ throw err
78
+ }
79
+
80
+ return entries
81
+ .filter((entry) => entry.isDirectory())
82
+ .map((entry) => entry.name)
83
+ .sort()
84
+ .reverse()
85
+ }
86
+
87
+ /** 按备份目录名回滚;id 必须精确匹配,避免误恢复。 */
88
+ export async function rollbackById(home, id) {
89
+ const available = await listBackups(home)
90
+ if (!available.includes(id)) {
91
+ return { restored: [], backup: null, error: `backup not found: ${id}`, available }
92
+ }
93
+
94
+ const dir = path.join(backupsDir(home), id)
95
+ const manifest = JSON.parse(await fs.readFile(path.join(dir, 'manifest.json'), 'utf8'))
96
+ const restored = []
97
+ for (const item of manifest.files) {
98
+ const source = path.join(dir, item.rel)
99
+ await fs.mkdir(path.dirname(item.file), { recursive: true })
100
+ await fs.copyFile(source, item.file)
101
+ restored.push(item.file)
102
+ }
103
+ return { restored, backup: dir, available }
104
+ }
@@ -0,0 +1,274 @@
1
+ import fs from 'node:fs/promises'
2
+ import path from 'node:path'
3
+ import { auditFile, profilePackageJson, resolveHome, resolveProfile, reportFile } from './paths.js'
4
+ import { loadGraph } from './graph.js'
5
+ import { buildPlan } from './plan.js'
6
+ import { applyPlan } from './apply.js'
7
+ import { createBackup, listBackups, rollback, rollbackById } from './backup.js'
8
+ import { readJson } from './load.js'
9
+ import { planIdFor, loadPlan, readState, saveGraph, savePlan, writeState } from './state.js'
10
+ import { dumpConfig } from './dumpconfig.js'
11
+ import { previewPlan } from './preview.js'
12
+ import { detectDshVersion, reinstallDependencies } from './installer.js'
13
+
14
+ async function context(options) {
15
+ const home = resolveHome(options.home)
16
+ const profile = resolveProfile(home, options.profile)
17
+ const graph = await loadGraph({
18
+ home,
19
+ ...profile,
20
+ probePort: options.probePort,
21
+ scanPorts: options.scanPorts,
22
+ scanLogs: options.scanLogs,
23
+ scanSources: options.scanSources,
24
+ logFile: options.logFile,
25
+ })
26
+ return { home, profile, graph }
27
+ }
28
+
29
+ function withMetadata(plan, graph) {
30
+ return {
31
+ ...plan,
32
+ id: plan.id ?? planIdFor(plan),
33
+ createdAt: plan.createdAt ?? new Date().toISOString(),
34
+ profile: graph.profile,
35
+ home: graph.home,
36
+ }
37
+ }
38
+
39
+ export async function runCheck(options = {}) {
40
+ const { home, graph } = await context(options)
41
+ const host = detectDshVersion({
42
+ home,
43
+ profile: graph.profile,
44
+ dshVersion: options.dshVersion,
45
+ app: options.app,
46
+ })
47
+ const previous = (await readState(home)).state?.hostVersion ?? null
48
+ graph.hostVersion = host.version
49
+ graph.hostChanged = Boolean(previous && host.version && previous !== host.version)
50
+
51
+ const graphFile = await saveGraph(home, graph)
52
+ await writeState(home, {
53
+ profile: graph.profile,
54
+ hostVersion: host.version,
55
+ hostChangedAt: graph.hostChanged ? new Date().toISOString() : undefined,
56
+ lastCheckAt: new Date().toISOString(),
57
+ conflicts: graph.conflicts.length,
58
+ })
59
+ return { graph, graphFile }
60
+ }
61
+
62
+ export async function runPlan(options = {}) {
63
+ const { home, profile, graph } = await context(options)
64
+ const plan = withMetadata(
65
+ buildPlan(graph, { allowPeerOverride: options.allowPeerOverride }),
66
+ graph,
67
+ )
68
+
69
+ const graphFile = await saveGraph(home, graph)
70
+ const saved = await savePlan(home, plan)
71
+ plan.id = saved.plan.id
72
+
73
+ if (options.diff !== false) {
74
+ plan.preview = await previewPlan({ home, graph, plan })
75
+ }
76
+
77
+ if (options.dumpConfig) {
78
+ plan.dumpConfig = await dumpConfig({
79
+ home,
80
+ profile: profile.profile,
81
+ dshBin: options.dshBin,
82
+ })
83
+ }
84
+
85
+ return { graph, plan, graphFile, planFile: saved.file }
86
+ }
87
+
88
+ export async function runApply(options = {}) {
89
+ const { home, graph } = await context(options)
90
+
91
+ let plan
92
+ if (options.planId) {
93
+ const loaded = await loadPlan(home, options.planId)
94
+ if (!loaded) throw new Error(`plan not found: ${options.planId}`)
95
+ plan = loaded.plan
96
+ } else {
97
+ plan = withMetadata(
98
+ buildPlan(graph, { allowPeerOverride: options.allowPeerOverride }),
99
+ graph,
100
+ )
101
+ }
102
+
103
+ if (!options.yes) {
104
+ return { graph, plan, applied: null, needsConfirm: true }
105
+ }
106
+
107
+ const saved = await savePlan(home, plan)
108
+ plan.id = saved.plan.id
109
+ const result = await applyPlan({ home, graph, plan })
110
+ await saveGraph(home, graph)
111
+ await writeState(home, {
112
+ profile: graph.profile,
113
+ lastApplied: {
114
+ planId: plan.id,
115
+ at: new Date().toISOString(),
116
+ actions: result.applied.length,
117
+ backup: result.backup,
118
+ },
119
+ })
120
+ return { graph, plan, ...result, needsConfirm: false }
121
+ }
122
+
123
+ export async function runRollback(options = {}) {
124
+ const home = resolveHome(options.home)
125
+ const result = options.id
126
+ ? await rollbackById(home, options.id)
127
+ : await rollback(home)
128
+ if (options.reinstall && result.backup) {
129
+ result.reinstall = await reinstallDependencies(options)
130
+ }
131
+ return result
132
+ }
133
+
134
+ export async function runReport(options = {}) {
135
+ const home = resolveHome(options.home)
136
+ const file = reportFile(home)
137
+ const report = await readJson(file)
138
+ return { file, exists: report != null, report }
139
+ }
140
+
141
+ export async function runList(options = {}) {
142
+ const home = resolveHome(options.home)
143
+ const profile = resolveProfile(home, options.profile)
144
+ const graph = await loadGraph({
145
+ home,
146
+ ...profile,
147
+ scanPorts: false,
148
+ scanLogs: false,
149
+ scanSources: false,
150
+ })
151
+ return {
152
+ home,
153
+ profile: graph.profile,
154
+ dir: graph.dir,
155
+ bundles: graph.bundleInfo.map((info) => ({
156
+ name: info.name,
157
+ version: info.version,
158
+ hasPatch: Boolean(info.patch),
159
+ patchError: info.patchError ?? null,
160
+ peers: info.peers,
161
+ })),
162
+ conflicts: graph.conflicts.map((conflict) => ({
163
+ type: conflict.resource.type,
164
+ key: conflict.resource.key,
165
+ owners: conflict.owners,
166
+ severity: conflict.severity,
167
+ })),
168
+ }
169
+ }
170
+
171
+ export async function runAudit(options = {}) {
172
+ const home = resolveHome(options.home)
173
+ const file = auditFile(home)
174
+ let text
175
+ try {
176
+ text = await fs.readFile(file, 'utf8')
177
+ } catch (err) {
178
+ if (err.code === 'ENOENT') return { file, exists: false, entries: [] }
179
+ throw err
180
+ }
181
+
182
+ const limit = Number.isInteger(options.limit) && options.limit > 0 ? options.limit : 20
183
+ const entries = []
184
+ for (const line of text.split(/\r?\n/)) {
185
+ if (!line.trim()) continue
186
+ try {
187
+ entries.push(JSON.parse(line))
188
+ } catch {
189
+ // 跳过损坏行,不让审计查询失败。
190
+ }
191
+ }
192
+
193
+ return { file, exists: true, entries: entries.slice(-limit).reverse() }
194
+ }
195
+
196
+ export async function runBackups(options = {}) {
197
+ const home = resolveHome(options.home)
198
+ const ids = await listBackups(home)
199
+ return { home, ids }
200
+ }
201
+
202
+ /**
203
+ * 调整 bundle 加载顺序:优先加载的插件会先注册,从而在冲突时保留原名。
204
+ * 只处理 dsh.profile.bundles 里的插件;写入前备份 package.json。
205
+ */
206
+ export async function runPrefer(options = {}) {
207
+ const home = resolveHome(options.home)
208
+ const profile = resolveProfile(home, options.profile)
209
+ const pkgFile = profilePackageJson(profile.dir)
210
+ const name = options.plugin ?? options.positional?.[0]
211
+ if (!name) return { ok: false, error: 'Usage: dsh-coexist prefer <plugin>' }
212
+
213
+ let manifest
214
+ try {
215
+ manifest = JSON.parse(await fs.readFile(pkgFile, 'utf8'))
216
+ } catch (err) {
217
+ return { ok: false, error: `Cannot read ${pkgFile}: ${err.message}` }
218
+ }
219
+
220
+ const bundles = manifest?.dsh?.profile?.bundles
221
+ if (!Array.isArray(bundles) || !bundles.includes(name)) {
222
+ return {
223
+ ok: false,
224
+ profile: profile.profile,
225
+ error: `plugin is not in dsh.profile.bundles: ${name}`,
226
+ order: Array.isArray(bundles) ? bundles : [],
227
+ }
228
+ }
229
+
230
+ // 只调整第三方插件段:官方 bundle 和 coexist 本身必须保持在前面。
231
+ let cut = bundles.indexOf('dsh-coexist-plugin')
232
+ if (cut < 0) {
233
+ cut = -1
234
+ while (cut + 1 < bundles.length && bundles[cut + 1].startsWith('@deepseek-ai/')) cut += 1
235
+ }
236
+ const head = bundles.slice(0, cut + 1)
237
+ const tail = bundles.slice(cut + 1)
238
+ if (!tail.includes(name)) {
239
+ return {
240
+ ok: false,
241
+ profile: profile.profile,
242
+ error: `plugin is pinned in front of the reorderable section: ${name}`,
243
+ order: bundles,
244
+ }
245
+ }
246
+
247
+ const next = [...head, name, ...tail.filter((item) => item !== name)]
248
+ if (next.join('\n') === bundles.join('\n')) {
249
+ return { ok: true, changed: false, profile: profile.profile, plugin: name, order: next }
250
+ }
251
+
252
+ const backup = await createBackup(home, [pkgFile])
253
+ manifest.dsh.profile.bundles = next
254
+ await fs.writeFile(pkgFile, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8')
255
+
256
+ await fs.mkdir(path.dirname(auditFile(home)), { recursive: true })
257
+ await fs.appendFile(
258
+ auditFile(home),
259
+ `${JSON.stringify({
260
+ at: new Date().toISOString(),
261
+ applied: [{ kind: 'prefer-bundle', plugin: name, order: next }],
262
+ backup: backup.dir,
263
+ })}\n`,
264
+ )
265
+
266
+ return {
267
+ ok: true,
268
+ changed: true,
269
+ profile: profile.profile,
270
+ plugin: name,
271
+ order: next,
272
+ backup: backup.dir,
273
+ }
274
+ }