dsh-plugin-update-center 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +149 -2
- package/client.js +1174 -0
- package/cordis.patch.yml +3 -0
- package/icon.svg +6 -0
- package/index.js +82 -0
- package/lib/backup.js +88 -0
- package/lib/engine.js +737 -0
- package/lib/http.js +141 -0
- package/lib/registry.js +156 -0
- package/lib/residue.js +246 -0
- package/lib/versions.js +211 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +66 -4
- package/repair.cmd +9 -0
- package/repair.mjs +130 -0
package/lib/http.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Same-origin HTTP face of the update engine.
|
|
3
|
+
*
|
|
4
|
+
* DSH's connection layer authenticates the browser peer; this route only
|
|
5
|
+
* accepts POST requests that carry the plugin's header and a bounded JSON body.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { errorCode } from './engine.js'
|
|
9
|
+
|
|
10
|
+
export const ROUTE = '/api/dsh-plugin-update-center'
|
|
11
|
+
const MAX_BODY_BYTES = 8 * 1024
|
|
12
|
+
const EXPECTED = new Set([
|
|
13
|
+
'busy',
|
|
14
|
+
'busy-session',
|
|
15
|
+
'check-first',
|
|
16
|
+
'release-changed',
|
|
17
|
+
'invalid-request',
|
|
18
|
+
'request-too-large',
|
|
19
|
+
'method-not-allowed',
|
|
20
|
+
'registry-unavailable',
|
|
21
|
+
'snapshot-failed',
|
|
22
|
+
'rollback-unavailable',
|
|
23
|
+
'verification-failed',
|
|
24
|
+
'dsh-update',
|
|
25
|
+
])
|
|
26
|
+
|
|
27
|
+
function respond(payload, status = 200) {
|
|
28
|
+
return new Response(JSON.stringify(payload), {
|
|
29
|
+
status,
|
|
30
|
+
headers: {
|
|
31
|
+
'content-type': 'application/json; charset=utf-8',
|
|
32
|
+
'cache-control': 'no-store',
|
|
33
|
+
'x-content-type-options': 'nosniff',
|
|
34
|
+
},
|
|
35
|
+
})
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function readBody(request, limit) {
|
|
39
|
+
const declared = request.headers.get('content-length')
|
|
40
|
+
if (declared !== null && Number(declared) > limit) throw Object.assign(new Error('request-too-large'), { code: 'request-too-large' })
|
|
41
|
+
if (request.body === null) return ''
|
|
42
|
+
const reader = request.body.getReader()
|
|
43
|
+
const chunks = []
|
|
44
|
+
let size = 0
|
|
45
|
+
try {
|
|
46
|
+
for (;;) {
|
|
47
|
+
const { done, value } = await reader.read()
|
|
48
|
+
if (done) break
|
|
49
|
+
size += value.byteLength
|
|
50
|
+
if (size > limit) {
|
|
51
|
+
await reader.cancel().catch(() => {})
|
|
52
|
+
throw Object.assign(new Error('request-too-large'), { code: 'request-too-large' })
|
|
53
|
+
}
|
|
54
|
+
chunks.push(value)
|
|
55
|
+
}
|
|
56
|
+
} finally {
|
|
57
|
+
reader.releaseLock?.()
|
|
58
|
+
}
|
|
59
|
+
const merged = new Uint8Array(size)
|
|
60
|
+
let offset = 0
|
|
61
|
+
for (const chunk of chunks) {
|
|
62
|
+
merged.set(chunk, offset)
|
|
63
|
+
offset += chunk.byteLength
|
|
64
|
+
}
|
|
65
|
+
return new TextDecoder().decode(merged)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function statusFor(code) {
|
|
69
|
+
if (code === 'request-too-large') return 413
|
|
70
|
+
if (code === 'method-not-allowed') return 405
|
|
71
|
+
if (code === 'registry-unavailable') return 502
|
|
72
|
+
if (code === 'snapshot-failed' || code === 'verification-failed') return 500
|
|
73
|
+
if (code === 'busy' || code === 'busy-session' || code === 'check-first' || code === 'rollback-unavailable' || code === 'dsh-update') return 409
|
|
74
|
+
return EXPECTED.has(code) ? 400 : 500
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Create the route handler for one engine.
|
|
79
|
+
* @param {ReturnType<import('./engine.js').createEngine>} engine
|
|
80
|
+
* @param {{ scan: Function, clean: Function } | null} [residue]
|
|
81
|
+
*/
|
|
82
|
+
export function createHandler(engine, residue = null) {
|
|
83
|
+
if (!engine || typeof engine.snapshot !== 'function') throw new TypeError('an update engine is required')
|
|
84
|
+
return async function handle(request) {
|
|
85
|
+
let action = 'unknown'
|
|
86
|
+
try {
|
|
87
|
+
if (request.method !== 'POST') return respond({ ok: false, code: 'method-not-allowed' }, 405)
|
|
88
|
+
if (request.headers.get('x-dsh-plugin-update-center') !== '1') return respond({ ok: false, code: 'invalid-request' }, 400)
|
|
89
|
+
const contentType = request.headers.get('content-type') ?? ''
|
|
90
|
+
if (!/^application\/json(?:;|$)/i.test(contentType)) return respond({ ok: false, code: 'invalid-request' }, 400)
|
|
91
|
+
const text = await readBody(request, MAX_BODY_BYTES)
|
|
92
|
+
let input
|
|
93
|
+
try {
|
|
94
|
+
input = text === '' ? {} : JSON.parse(text)
|
|
95
|
+
} catch {
|
|
96
|
+
return respond({ ok: false, code: 'invalid-request' }, 400)
|
|
97
|
+
}
|
|
98
|
+
if (input === null || typeof input !== 'object' || Array.isArray(input)) return respond({ ok: false, code: 'invalid-request' }, 400)
|
|
99
|
+
action = typeof input.action === 'string' ? input.action : 'unknown'
|
|
100
|
+
switch (action) {
|
|
101
|
+
case 'state':
|
|
102
|
+
return respond({ ok: true, value: engine.snapshot() })
|
|
103
|
+
case 'check':
|
|
104
|
+
return respond({ ok: true, value: await engine.check({ force: input.force === true }) })
|
|
105
|
+
case 'start':
|
|
106
|
+
return respond({ ok: true, value: await engine.start(input.names, { waitForIdle: input.waitForIdle === true }) })
|
|
107
|
+
case 'cancel':
|
|
108
|
+
return respond({ ok: true, value: engine.cancel() })
|
|
109
|
+
case 'reload-ack':
|
|
110
|
+
return respond({
|
|
111
|
+
ok: true,
|
|
112
|
+
value: engine.acknowledgeReload(typeof input.jobId === 'string' ? input.jobId : undefined),
|
|
113
|
+
})
|
|
114
|
+
case 'desktop-update':
|
|
115
|
+
return respond({ ok: true, value: engine.setDesktopUpdate({ phase: input.phase, version: input.version }) })
|
|
116
|
+
case 'residue':
|
|
117
|
+
return respond({
|
|
118
|
+
ok: true,
|
|
119
|
+
value: residue === null
|
|
120
|
+
? { checkedAt: Date.now(), items: [], cleanable: 0, error: null }
|
|
121
|
+
: await residue.scan(),
|
|
122
|
+
})
|
|
123
|
+
case 'clean-residue':
|
|
124
|
+
return respond({
|
|
125
|
+
ok: true,
|
|
126
|
+
value: residue === null
|
|
127
|
+
? { cleaned: [], residue: { checkedAt: Date.now(), items: [], cleanable: 0, error: null } }
|
|
128
|
+
: await residue.clean(),
|
|
129
|
+
})
|
|
130
|
+
case 'dismiss':
|
|
131
|
+
return respond({ ok: true, value: engine.dismiss() })
|
|
132
|
+
default:
|
|
133
|
+
return respond({ ok: false, code: 'invalid-request' }, 400)
|
|
134
|
+
}
|
|
135
|
+
} catch (error) {
|
|
136
|
+
const code = errorCode(error)
|
|
137
|
+
if (!EXPECTED.has(code)) console.warn('[dsh-plugin-update-center] %s failed:', action, code)
|
|
138
|
+
return respond({ ok: false, code }, statusFor(code))
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
package/lib/registry.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* npm registry access for the update checker.
|
|
3
|
+
*
|
|
4
|
+
* Only public registry metadata is read. The official DSH plugin manager owns
|
|
5
|
+
* the actual installation; this module never writes packages or profile files.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { parseVersion } from './versions.js'
|
|
9
|
+
|
|
10
|
+
export const DEFAULT_REGISTRIES = Object.freeze([
|
|
11
|
+
'https://registry.npmjs.org',
|
|
12
|
+
'https://registry.npmmirror.com',
|
|
13
|
+
])
|
|
14
|
+
|
|
15
|
+
const USER_AGENT = 'dsh-plugin-update-center/1.0.0'
|
|
16
|
+
|
|
17
|
+
/** One bounded registry failure expressed as a stable code. */
|
|
18
|
+
export class RegistryError extends Error {
|
|
19
|
+
constructor(code) {
|
|
20
|
+
super(code)
|
|
21
|
+
this.name = 'RegistryError'
|
|
22
|
+
this.code = code
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function readBounded(stream, limit, signal) {
|
|
27
|
+
const reader = stream.getReader()
|
|
28
|
+
const chunks = []
|
|
29
|
+
let size = 0
|
|
30
|
+
try {
|
|
31
|
+
for (;;) {
|
|
32
|
+
signal?.throwIfAborted()
|
|
33
|
+
const { done, value } = await reader.read()
|
|
34
|
+
if (done) break
|
|
35
|
+
size += value.byteLength
|
|
36
|
+
if (size > limit) {
|
|
37
|
+
await reader.cancel().catch(() => {})
|
|
38
|
+
throw new RegistryError('registry-response-too-large')
|
|
39
|
+
}
|
|
40
|
+
chunks.push(value)
|
|
41
|
+
}
|
|
42
|
+
} finally {
|
|
43
|
+
reader.releaseLock?.()
|
|
44
|
+
}
|
|
45
|
+
const merged = new Uint8Array(size)
|
|
46
|
+
let offset = 0
|
|
47
|
+
for (const chunk of chunks) {
|
|
48
|
+
merged.set(chunk, offset)
|
|
49
|
+
offset += chunk.byteLength
|
|
50
|
+
}
|
|
51
|
+
return new TextDecoder().decode(merged)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Create the registry client used by the engine.
|
|
56
|
+
* @param {object} [options]
|
|
57
|
+
* @param {typeof fetch} [options.fetchImpl] fetch implementation (tests inject one)
|
|
58
|
+
* @param {number} [options.timeoutMs] per-request timeout
|
|
59
|
+
* @param {readonly string[]} [options.registries] registries asked in order
|
|
60
|
+
* @param {number} [options.maxBytes] response size cap
|
|
61
|
+
*/
|
|
62
|
+
export function createRegistry({
|
|
63
|
+
fetchImpl = globalThis.fetch,
|
|
64
|
+
timeoutMs = 15000,
|
|
65
|
+
registries = DEFAULT_REGISTRIES,
|
|
66
|
+
maxBytes = 4 * 1024 * 1024,
|
|
67
|
+
} = {}) {
|
|
68
|
+
if (typeof fetchImpl !== 'function') throw new TypeError('fetch implementation is required')
|
|
69
|
+
const bases = registries.filter((base) => typeof base === 'string' && /^https?:\/\//.test(base))
|
|
70
|
+
if (bases.length === 0) throw new TypeError('at least one registry is required')
|
|
71
|
+
|
|
72
|
+
async function json(url, signal) {
|
|
73
|
+
const timeout = AbortSignal.timeout(timeoutMs)
|
|
74
|
+
const combined = signal === undefined ? timeout : AbortSignal.any([signal, timeout])
|
|
75
|
+
const response = await fetchImpl(url, {
|
|
76
|
+
redirect: 'error',
|
|
77
|
+
signal: combined,
|
|
78
|
+
headers: { accept: 'application/json', 'user-agent': USER_AGENT },
|
|
79
|
+
})
|
|
80
|
+
if (!response.ok || response.body === null) {
|
|
81
|
+
await response.body?.cancel().catch(() => {})
|
|
82
|
+
throw new RegistryError(`registry-http-${response.status}`)
|
|
83
|
+
}
|
|
84
|
+
const text = await readBounded(response.body, maxBytes, combined)
|
|
85
|
+
try {
|
|
86
|
+
return JSON.parse(text)
|
|
87
|
+
} catch {
|
|
88
|
+
throw new RegistryError('registry-invalid-json')
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function validVersion(value) {
|
|
93
|
+
return typeof value === 'string' && parseVersion(value) !== null
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function distTag(base, name, signal) {
|
|
97
|
+
const encoded = encodeURIComponent(name)
|
|
98
|
+
try {
|
|
99
|
+
const tags = await json(`${base}/-/package/${encoded}/dist-tags`, signal)
|
|
100
|
+
if (validVersion(tags?.latest)) return tags.latest
|
|
101
|
+
} catch (error) {
|
|
102
|
+
signal?.throwIfAborted()
|
|
103
|
+
}
|
|
104
|
+
const packument = await json(`${base}/${encoded}`, signal)
|
|
105
|
+
if (validVersion(packument?.['dist-tags']?.latest)) return packument['dist-tags'].latest
|
|
106
|
+
throw new RegistryError('registry-no-latest')
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function latest(name, signal) {
|
|
110
|
+
let lastError
|
|
111
|
+
for (const base of bases) {
|
|
112
|
+
try {
|
|
113
|
+
return { version: await distTag(base, name, signal), registry: base }
|
|
114
|
+
} catch (error) {
|
|
115
|
+
signal?.throwIfAborted()
|
|
116
|
+
lastError = error
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
throw lastError ?? new RegistryError('registry-unavailable')
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function manifest(name, version, signal, preferred) {
|
|
123
|
+
const encoded = encodeURIComponent(name)
|
|
124
|
+
const order = preferred === undefined
|
|
125
|
+
? bases
|
|
126
|
+
: [preferred, ...bases.filter((base) => base !== preferred)]
|
|
127
|
+
let lastError
|
|
128
|
+
for (const base of order) {
|
|
129
|
+
try {
|
|
130
|
+
const document = await json(`${base}/${encoded}/${version}`, signal)
|
|
131
|
+
if (document?.name !== name || document?.version !== version) throw new RegistryError('registry-version-mismatch')
|
|
132
|
+
return { manifest: document, registry: base }
|
|
133
|
+
} catch (error) {
|
|
134
|
+
signal?.throwIfAborted()
|
|
135
|
+
lastError = error
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
throw lastError ?? new RegistryError('registry-unavailable')
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Resolve one release. Without `version` the registry `latest` tag is used.
|
|
143
|
+
* @param {string} name package name
|
|
144
|
+
* @param {AbortSignal} [signal]
|
|
145
|
+
* @param {{ version?: string }} [options]
|
|
146
|
+
*/
|
|
147
|
+
async function release(name, signal, options = {}) {
|
|
148
|
+
const resolved = options.version === undefined
|
|
149
|
+
? await latest(name, signal)
|
|
150
|
+
: { version: options.version, registry: undefined }
|
|
151
|
+
const found = await manifest(name, resolved.version, signal, resolved.registry)
|
|
152
|
+
return { version: resolved.version, registry: found.registry, manifest: found.manifest }
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
return { latest, manifest, release }
|
|
156
|
+
}
|
package/lib/residue.js
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Leftover-reference scanner for the active profile.
|
|
3
|
+
*
|
|
4
|
+
* The official uninstall removes the dependency, the bundle selection and the
|
|
5
|
+
* package files. What remains is profile configuration that still names a
|
|
6
|
+
* package: a dangling `dsh.profile.bundles` entry, a user patch row, or a
|
|
7
|
+
* plugin data directory. Only the dangling selection is safe to remove
|
|
8
|
+
* automatically; the rest is reported for a manual decision.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { existsSync } from 'node:fs'
|
|
12
|
+
import { readFile, rename, writeFile } from 'node:fs/promises'
|
|
13
|
+
import { join } from 'node:path'
|
|
14
|
+
|
|
15
|
+
const PATCH_FILE = 'cordis.patch.yml'
|
|
16
|
+
const MANIFEST_FILE = 'package.json'
|
|
17
|
+
const OFFICIAL_PREFIX = '@deepseek-ai/'
|
|
18
|
+
const PACKAGE_NAME = /^(?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*(?:\/[\w.-]+)?$/i
|
|
19
|
+
|
|
20
|
+
function packageRootOf(value) {
|
|
21
|
+
if (/[:\\/]/.test(value) && !value.startsWith('@')) return null
|
|
22
|
+
if (value.startsWith('@')) {
|
|
23
|
+
const parts = value.split('/')
|
|
24
|
+
return parts.length >= 2 ? parts[0] + '/' + parts[1] : null
|
|
25
|
+
}
|
|
26
|
+
return value.split('/')[0]
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function isModuleName(value) {
|
|
30
|
+
if (!PACKAGE_NAME.test(value)) return false
|
|
31
|
+
if (value.startsWith('@')) return true
|
|
32
|
+
return value.includes('-') || value.includes('/') || value.startsWith('dsh-')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function scanPatchReferences(text, profileDir) {
|
|
36
|
+
const items = []
|
|
37
|
+
const lines = text.split(/\r?\n/)
|
|
38
|
+
let inInsert = false
|
|
39
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
40
|
+
const line = lines[index]
|
|
41
|
+
if (/^-\s+insert:/.test(line)) {
|
|
42
|
+
inInsert = true
|
|
43
|
+
continue
|
|
44
|
+
}
|
|
45
|
+
if (/^-\s+/.test(line)) inInsert = false
|
|
46
|
+
const match = /^(\s*)name:\s*['"]?([^'"\s#]+)['"]?\s*(?:#.*)?$/.exec(line)
|
|
47
|
+
if (match === null) continue
|
|
48
|
+
const indent = match[1].length
|
|
49
|
+
const value = match[2]
|
|
50
|
+
if (!isModuleName(value)) continue
|
|
51
|
+
if (value.startsWith(OFFICIAL_PREFIX)) continue
|
|
52
|
+
if (inInsert === false && indent > 2) continue
|
|
53
|
+
const root = packageRootOf(value)
|
|
54
|
+
if (root === null) continue
|
|
55
|
+
if (existsSync(join(profileDir, 'node_modules', root, MANIFEST_FILE))) continue
|
|
56
|
+
items.push({ kind: 'patch', name: value, line: index + 1, text: line.trim() })
|
|
57
|
+
}
|
|
58
|
+
return items
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function scanDataDirectories(danglingNames, homeDir) {
|
|
62
|
+
const items = []
|
|
63
|
+
for (const name of danglingNames) {
|
|
64
|
+
if (typeof name !== 'string' || name.includes('/') || name.includes('\\')) continue
|
|
65
|
+
const path = join(homeDir, name)
|
|
66
|
+
if (!existsSync(path)) continue
|
|
67
|
+
items.push({ kind: 'data', name, path })
|
|
68
|
+
}
|
|
69
|
+
return items
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Scan one profile for leftover references.
|
|
74
|
+
* @param {object} options
|
|
75
|
+
* @param {string} options.profileDir
|
|
76
|
+
* @param {string} options.homeDir
|
|
77
|
+
* @param {object} options.manager pluginManager (listBundles)
|
|
78
|
+
*/
|
|
79
|
+
export async function scanResidue({ profileDir, homeDir, manager }) {
|
|
80
|
+
const checkedAt = Date.now()
|
|
81
|
+
let manifest
|
|
82
|
+
try {
|
|
83
|
+
manifest = JSON.parse(await readFile(join(profileDir, MANIFEST_FILE), 'utf8'))
|
|
84
|
+
} catch {
|
|
85
|
+
return { checkedAt, items: [], cleanable: 0, error: 'manifest-unreadable' }
|
|
86
|
+
}
|
|
87
|
+
const dependencies = manifest?.dependencies ?? {}
|
|
88
|
+
const bundles = Array.isArray(manifest?.dsh?.profile?.bundles) ? manifest.dsh.profile.bundles : []
|
|
89
|
+
let rows = []
|
|
90
|
+
try {
|
|
91
|
+
if (typeof manager?.listBundles === 'function') rows = await manager.listBundles()
|
|
92
|
+
} catch {
|
|
93
|
+
rows = []
|
|
94
|
+
}
|
|
95
|
+
const installed = new Set(Object.keys(dependencies))
|
|
96
|
+
const shipped = new Set()
|
|
97
|
+
const catalog = new Set()
|
|
98
|
+
for (const row of Array.isArray(rows) ? rows : []) {
|
|
99
|
+
if (!row || typeof row.name !== 'string') continue
|
|
100
|
+
if (row.availability === 'installation') shipped.add(row.name)
|
|
101
|
+
if (row.installTarget !== undefined) catalog.add(row.name)
|
|
102
|
+
}
|
|
103
|
+
const items = []
|
|
104
|
+
const dangling = []
|
|
105
|
+
for (const name of bundles) {
|
|
106
|
+
if (typeof name !== 'string') continue
|
|
107
|
+
if (installed.has(name) || shipped.has(name) || catalog.has(name)) continue
|
|
108
|
+
const row = rows.find((entry) => entry?.name === name)
|
|
109
|
+
if (row?.installed === true) continue
|
|
110
|
+
dangling.push(name)
|
|
111
|
+
items.push({ kind: 'selection', name, detail: row?.error?.code ?? 'missing' })
|
|
112
|
+
}
|
|
113
|
+
let patchText
|
|
114
|
+
try {
|
|
115
|
+
patchText = await readFile(join(profileDir, PATCH_FILE), 'utf8')
|
|
116
|
+
} catch {
|
|
117
|
+
patchText = null
|
|
118
|
+
}
|
|
119
|
+
if (typeof patchText === 'string') items.push(...scanPatchReferences(patchText, profileDir))
|
|
120
|
+
if (typeof homeDir === 'string' && homeDir !== '') items.push(...scanDataDirectories(dangling, homeDir))
|
|
121
|
+
return {
|
|
122
|
+
checkedAt,
|
|
123
|
+
items,
|
|
124
|
+
cleanable: items.filter((item) => item.kind === 'selection' || item.kind === 'patch').length,
|
|
125
|
+
error: null,
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Remove the YAML blocks that carry dangling `name:` lines.
|
|
131
|
+
*
|
|
132
|
+
* A top-level override is removed whole. Inside an `- insert:` block only the
|
|
133
|
+
* child item that owns the dangling line is removed. Other lines, comments and
|
|
134
|
+
* formatting stay byte-for-byte untouched; the caller validates and writes
|
|
135
|
+
* atomically.
|
|
136
|
+
*/
|
|
137
|
+
function stripPatchItems(text, danglingLines) {
|
|
138
|
+
const lines = text.split(/\r?\n/)
|
|
139
|
+
const remove = new Set()
|
|
140
|
+
const removed = []
|
|
141
|
+
const tops = []
|
|
142
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
143
|
+
if (/^-\s/.test(lines[index])) tops.push(index)
|
|
144
|
+
}
|
|
145
|
+
for (let position = 0; position < tops.length; position += 1) {
|
|
146
|
+
const start = tops[position]
|
|
147
|
+
const end = position + 1 < tops.length ? tops[position + 1] : lines.length
|
|
148
|
+
const hits = danglingLines.filter((line) => line - 1 >= start && line - 1 < end)
|
|
149
|
+
if (hits.length === 0) continue
|
|
150
|
+
const isInsert = /^-\s+insert:/.test(lines[start])
|
|
151
|
+
if (!isInsert) {
|
|
152
|
+
for (let index = start; index < end; index += 1) remove.add(index)
|
|
153
|
+
removed.push({ kind: 'patch', from: start + 1, to: end, count: hits.length })
|
|
154
|
+
continue
|
|
155
|
+
}
|
|
156
|
+
let childIndent = null
|
|
157
|
+
for (let index = start + 1; index < end; index += 1) {
|
|
158
|
+
const match = /^(\s+)-\s/.exec(lines[index])
|
|
159
|
+
if (match !== null) {
|
|
160
|
+
childIndent = match[1].length
|
|
161
|
+
break
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (childIndent === null) continue
|
|
165
|
+
const prefix = ' '.repeat(childIndent) + '- '
|
|
166
|
+
const children = []
|
|
167
|
+
for (let index = start + 1; index < end; index += 1) {
|
|
168
|
+
if (lines[index].startsWith(prefix)) children.push(index)
|
|
169
|
+
}
|
|
170
|
+
for (let child = 0; child < children.length; child += 1) {
|
|
171
|
+
const childStart = children[child]
|
|
172
|
+
const childEnd = child + 1 < children.length ? children[child + 1] : end
|
|
173
|
+
const childHits = danglingLines.filter((line) => line - 1 >= childStart && line - 1 < childEnd)
|
|
174
|
+
if (childHits.length === 0) continue
|
|
175
|
+
for (let index = childStart; index < childEnd; index += 1) remove.add(index)
|
|
176
|
+
removed.push({ kind: 'patch', from: childStart + 1, to: childEnd, count: childHits.length })
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return { text: lines.filter((_, index) => !remove.has(index)).join('\n'), removed }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function writeAtomic(path, text) {
|
|
183
|
+
const temporary = path + '.residue-' + Date.now() + '.tmp'
|
|
184
|
+
await writeFile(temporary, text, 'utf8')
|
|
185
|
+
await rename(temporary, path)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Clean dangling selections and dangling patch rows. Data directories are
|
|
190
|
+
* never touched. The profile files are snapshotted first and written
|
|
191
|
+
* atomically; the patch text keeps every untouched line verbatim.
|
|
192
|
+
*/
|
|
193
|
+
export async function cleanResidue({ profileDir, homeDir, manager, backup }) {
|
|
194
|
+
const before = await scanResidue({ profileDir, homeDir, manager })
|
|
195
|
+
const selectionNames = before.items.filter((item) => item.kind === 'selection').map((item) => item.name)
|
|
196
|
+
const patchLines = before.items.filter((item) => item.kind === 'patch').map((item) => item.line)
|
|
197
|
+
if (selectionNames.length === 0 && patchLines.length === 0) {
|
|
198
|
+
return { cleaned: [], residue: before }
|
|
199
|
+
}
|
|
200
|
+
await backup?.create?.({ reason: 'residue-cleanup', selections: selectionNames, patchLines })
|
|
201
|
+
const cleaned = []
|
|
202
|
+
|
|
203
|
+
if (selectionNames.length > 0) {
|
|
204
|
+
const manifestPath = join(profileDir, MANIFEST_FILE)
|
|
205
|
+
const manifest = JSON.parse(await readFile(manifestPath, 'utf8'))
|
|
206
|
+
const current = Array.isArray(manifest?.dsh?.profile?.bundles) ? manifest.dsh.profile.bundles : []
|
|
207
|
+
const removable = new Set(selectionNames.filter((name) => current.includes(name)))
|
|
208
|
+
if (removable.size > 0) {
|
|
209
|
+
manifest.dsh = {
|
|
210
|
+
...manifest.dsh,
|
|
211
|
+
profile: {
|
|
212
|
+
...manifest.dsh?.profile,
|
|
213
|
+
bundles: current.filter((name) => !removable.has(name)),
|
|
214
|
+
},
|
|
215
|
+
}
|
|
216
|
+
const next = JSON.stringify(manifest, null, 2) + '\n'
|
|
217
|
+
JSON.parse(next)
|
|
218
|
+
await writeAtomic(manifestPath, next)
|
|
219
|
+
cleaned.push(...[...removable].map((name) => ({ kind: 'selection', name })))
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (patchLines.length > 0) {
|
|
224
|
+
const patchPath = join(profileDir, PATCH_FILE)
|
|
225
|
+
const original = await readFile(patchPath, 'utf8')
|
|
226
|
+
const stripped = stripPatchItems(original, patchLines)
|
|
227
|
+
if (stripped.text !== original) {
|
|
228
|
+
const removedPatchNames = before.items
|
|
229
|
+
.filter((item) => item.kind === "patch" && stripped.removed.some((range) => item.line >= range.from && item.line <= range.to))
|
|
230
|
+
.map((item) => item.name)
|
|
231
|
+
await writeAtomic(patchPath, stripped.text)
|
|
232
|
+
cleaned.push(...removedPatchNames.map((name) => ({ kind: "patch", name })))
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
return { cleaned, residue: await scanResidue({ profileDir, homeDir, manager }) }
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Service wrapper used by the HTTP route. */
|
|
240
|
+
export function createResidueService({ profileDir, homeDir, manager, backup }) {
|
|
241
|
+
if (typeof profileDir !== 'string' || profileDir === '') throw new TypeError('profileDir is required')
|
|
242
|
+
return {
|
|
243
|
+
scan: () => scanResidue({ profileDir, homeDir, manager }),
|
|
244
|
+
clean: () => cleanResidue({ profileDir, homeDir, manager, backup }),
|
|
245
|
+
}
|
|
246
|
+
}
|