dsh-version-manager 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.
@@ -0,0 +1,335 @@
1
+ /**
2
+ * Snapshots: what was installed before a change, in a form that can be checked
3
+ * later instead of trusted.
4
+ *
5
+ * A snapshot is not a backup of a dependency tree and cannot pretend to be one.
6
+ * It records the handful of facts that make "put it back" decidable:
7
+ *
8
+ * which profile, which package, what spec the profile declared, which version
9
+ * was actually resolved, where it came from, whether it was enabled, and a
10
+ * fingerprint of the installed files.
11
+ *
12
+ * Restoring is then offered only when the fingerprint still matches, because a
13
+ * snapshot of `1.2.3` is worthless if the files on disk stopped being `1.2.3`.
14
+ *
15
+ * On disk: `<dshHome>/version-manager/snapshots/<profileId>/<targetId>/<seq>-<id>.json`.
16
+ * Writes go to a temporary file in the same directory and are renamed into place,
17
+ * so a crash leaves either the old set of snapshots or the new one and never a
18
+ * half-written file. An existing snapshot is never overwritten.
19
+ *
20
+ * @module dsh-version-manager/lib/host/snapshot-store
21
+ */
22
+
23
+ import { createHash, randomUUID } from 'node:crypto'
24
+ import { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
25
+ import { join } from 'node:path'
26
+
27
+ /** Bumped whenever the shape below changes in a way old readers cannot read. */
28
+ export const SNAPSHOT_SCHEMA = 1
29
+
30
+ /** How many snapshots survive per target. Older ones are reported, not deleted. */
31
+ export const SNAPSHOT_KEEP = 20
32
+
33
+ /**
34
+ * A filename-safe form of a package name.
35
+ *
36
+ * `@scope/name` would otherwise create a directory, and a name is not a path.
37
+ *
38
+ * @param {string} targetId
39
+ * @returns {string}
40
+ */
41
+ export function encodeTarget(targetId) {
42
+ return targetId.replace(/\//g, '%2F').replace(/[^A-Za-z0-9%._@-]/g, '_')
43
+ }
44
+
45
+ /**
46
+ * Where snapshots for one profile live.
47
+ *
48
+ * @param {string} dshHome
49
+ * @param {string} profileId
50
+ * @returns {string}
51
+ */
52
+ export function snapshotRoot(dshHome, profileId) {
53
+ return join(dshHome, 'version-manager', 'snapshots', encodeTarget(profileId))
54
+ }
55
+
56
+ /**
57
+ * A stable fingerprint of a directory tree: relative path plus content hash.
58
+ *
59
+ * Only regular files contribute. Symbolic links are recorded as a link to their
60
+ * target string, because following them would let a fingerprint depend on files
61
+ * outside the package and could loop.
62
+ *
63
+ * @param {import('node:fs').PathLike} root
64
+ * @param {AbortSignal} [signal]
65
+ * @returns {Promise<{ digest: string, files: number, bytes: number } | null>}
66
+ */
67
+ export async function fingerprintTree(root, signal) {
68
+ const { readdir: read, lstat, readlink } = await import('node:fs/promises')
69
+ const { createReadStream } = await import('node:fs')
70
+
71
+ let files = 0
72
+ let bytes = 0
73
+ const digest = createHash('sha256')
74
+
75
+ /** @param {string} directory @param {string} prefix */
76
+ async function walk(directory, prefix) {
77
+ const entries = await read(directory, { withFileTypes: true })
78
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
79
+ for (const entry of entries) {
80
+ if (signal?.aborted === true) throw new Error('aborted')
81
+ const full = join(directory, entry.name)
82
+ const relative = prefix === '' ? entry.name : `${prefix}/${entry.name}`
83
+ if (entry.isDirectory()) {
84
+ await walk(full, relative)
85
+ continue
86
+ }
87
+ if (entry.isSymbolicLink()) {
88
+ const target = await readlink(full)
89
+ digest.update(`link\0${relative}\0${target}\0`)
90
+ files += 1
91
+ continue
92
+ }
93
+ if (!entry.isFile()) continue
94
+ const info = await lstat(full)
95
+ const hash = await hashFile(full)
96
+ digest.update(`file\0${relative}\0${info.size}\0${hash}\0`)
97
+ files += 1
98
+ bytes += info.size
99
+ }
100
+ }
101
+
102
+ /**
103
+ * @param {string} path
104
+ * @returns {Promise<string>}
105
+ */
106
+ function hashFile(path) {
107
+ return new Promise((resolve, reject) => {
108
+ const hash = createHash('sha256')
109
+ const stream = createReadStream(path)
110
+ stream.on('data', (chunk) => hash.update(chunk))
111
+ stream.on('error', reject)
112
+ stream.on('end', () => resolve(hash.digest('hex')))
113
+ })
114
+ }
115
+
116
+ try {
117
+ await walk(String(root), '')
118
+ } catch (error) {
119
+ if (error?.code === 'ENOENT') return null
120
+ throw error
121
+ }
122
+ return { digest: digest.digest('hex'), files, bytes }
123
+ }
124
+
125
+ /**
126
+ * Take one snapshot.
127
+ *
128
+ * @param {object} input
129
+ * @param {string} input.dshHome
130
+ * @param {string} input.profileId
131
+ * @param {object} input.target - an inventory row
132
+ * @param {object | null} input.fingerprint
133
+ * @param {string} [input.reason]
134
+ * @returns {Promise<object>} the stored document
135
+ */
136
+ export async function writeSnapshot(input) {
137
+ const { dshHome, profileId, target, fingerprint, reason } = input
138
+ const directory = join(snapshotRoot(dshHome, profileId), encodeTarget(target.targetId))
139
+ await mkdir(directory, { recursive: true })
140
+
141
+ const existing = await listSnapshots(dshHome, profileId, target.targetId)
142
+ const seq = existing.length === 0 ? 1 : Math.max(...existing.map((row) => row.seq)) + 1
143
+
144
+ const document = {
145
+ schema: SNAPSHOT_SCHEMA,
146
+ id: randomUUID(),
147
+ seq,
148
+ takenAt: new Date().toISOString(),
149
+ reason: typeof reason === 'string' ? reason : 'manual',
150
+ profile: { id: profileId },
151
+ target: {
152
+ kind: target.kind,
153
+ targetId: target.targetId,
154
+ declaredSpec: target.declaredSpec,
155
+ installedVersion: target.installedVersion,
156
+ source: {
157
+ kind: target.source.kind,
158
+ registryName: target.source.registryName,
159
+ registryRange: target.source.registryRange,
160
+ // The registry host the package came from, when the lockfile recorded
161
+ // one. Reinstalling through a different registry is a different
162
+ // artifact set, so a restore points back at where it was taken from.
163
+ registry: target.source.registry ?? null,
164
+ // The detail can be a local path; it is kept because a recovery needs it
165
+ // and stripped from anything that leaves this machine.
166
+ detail: target.source.detail,
167
+ },
168
+ enabledState: target.enabledState,
169
+ compatibility: { verdict: target.compatibility.verdict },
170
+ fingerprint,
171
+ },
172
+ // Deliberately absent: tokens, credentials, environment variables, secrets
173
+ // from configuration, and the contents of any file.
174
+ environment: {
175
+ ...(process.platform === undefined ? {} : { platform: process.platform }),
176
+ node: process.versions?.node ?? null,
177
+ },
178
+ }
179
+
180
+ const body = `${JSON.stringify(document, null, 2)}\n`
181
+ const temporary = join(directory, `.${document.id}.tmp`)
182
+ await writeFile(temporary, body, { encoding: 'utf8', flag: 'wx' })
183
+ await rename(temporary, join(directory, `${String(seq).padStart(4, '0')}-${document.id}.json`))
184
+ return document
185
+ }
186
+
187
+ /**
188
+ * Every snapshot for one target, oldest first.
189
+ *
190
+ * A file that does not parse is reported as unreadable rather than throwing: a
191
+ * corrupt snapshot must not hide the healthy ones beside it.
192
+ *
193
+ * @param {string} dshHome
194
+ * @param {string} profileId
195
+ * @param {string} targetId
196
+ * @returns {Promise<object[]>}
197
+ */
198
+ export async function listSnapshots(dshHome, profileId, targetId) {
199
+ const directory = join(snapshotRoot(dshHome, profileId), encodeTarget(targetId))
200
+ let names
201
+ try {
202
+ names = await readdir(directory)
203
+ } catch (error) {
204
+ if (error?.code === 'ENOENT') return []
205
+ throw error
206
+ }
207
+
208
+ const rows = []
209
+ for (const name of names) {
210
+ if (!name.endsWith('.json')) continue
211
+ try {
212
+ const text = await readFile(join(directory, name), 'utf8')
213
+ const document = JSON.parse(text)
214
+ if (document?.schema !== SNAPSHOT_SCHEMA) continue
215
+ rows.push({
216
+ seq: typeof document.seq === 'number' ? document.seq : 0,
217
+ id: document.id,
218
+ takenAt: document.takenAt,
219
+ reason: document.reason,
220
+ installedVersion: document.target?.installedVersion ?? null,
221
+ declaredSpec: document.target?.declaredSpec ?? null,
222
+ fingerprint: document.target?.fingerprint ?? null,
223
+ file: name,
224
+ })
225
+ } catch {
226
+ rows.push({
227
+ seq: 0,
228
+ id: null,
229
+ takenAt: null,
230
+ reason: 'unreadable',
231
+ installedVersion: null,
232
+ declaredSpec: null,
233
+ fingerprint: null,
234
+ file: name,
235
+ })
236
+ }
237
+ }
238
+ rows.sort((a, b) => a.seq - b.seq)
239
+ return rows
240
+ }
241
+
242
+ /**
243
+ * Which snapshots are beyond the retention limit.
244
+ *
245
+ * Returned rather than deleted: a version manager that quietly removes evidence
246
+ * is worse than one that keeps too much. The caller may prune only after the
247
+ * user asked for it.
248
+ *
249
+ * @param {object[]} snapshots
250
+ * @param {number} [keep]
251
+ * @returns {object[]}
252
+ */
253
+ export function snapshotsBeyondRetention(snapshots, keep = SNAPSHOT_KEEP) {
254
+ if (snapshots.length <= keep) return []
255
+ return snapshots.slice(0, snapshots.length - keep)
256
+ }
257
+
258
+ /**
259
+ * Delete one snapshot by file name.
260
+ *
261
+ * @param {string} dshHome
262
+ * @param {string} profileId
263
+ * @param {string} targetId
264
+ * @param {string} file
265
+ * @returns {Promise<boolean>}
266
+ */
267
+ export async function deleteSnapshot(dshHome, profileId, targetId, file) {
268
+ // The name comes from a listing, but it is still a filename from a request
269
+ // path in the worst case: refuse anything that is not a plain file name.
270
+ if (typeof file !== 'string' || file.includes('/') || file.includes('\\') || file.includes('..')) {
271
+ return false
272
+ }
273
+ const path = join(snapshotRoot(dshHome, profileId), encodeTarget(targetId), file)
274
+ try {
275
+ await rm(path)
276
+ return true
277
+ } catch {
278
+ return false
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Can this snapshot be restored right now?
284
+ *
285
+ * Three conditions, each with its own sentence, because "no" for the wrong
286
+ * reason sends the user looking in the wrong place:
287
+ *
288
+ * 1. the recorded spec is one the host can install again
289
+ * 2. the files on disk still match the fingerprint that was taken
290
+ * 3. a version was actually recorded
291
+ *
292
+ * @param {object} snapshot
293
+ * @param {object | null} currentFingerprint
294
+ * @returns {{ ok: boolean, reason: string | null, detail: string | null }}
295
+ */
296
+ export function recoveryVerdict(snapshot, currentFingerprint) {
297
+ const target = snapshot?.target
298
+ if (target === undefined || target === null) {
299
+ return { ok: false, reason: 'snapshot-incomplete', detail: 'The snapshot has no target record.', filesMatch: null }
300
+ }
301
+ if (typeof target.installedVersion !== 'string' || target.installedVersion === '') {
302
+ return { ok: false, reason: 'no-version', detail: 'The snapshot recorded no installed version.', filesMatch: null }
303
+ }
304
+ if (target.source?.kind !== 'registry' || typeof target.source?.registryName !== 'string') {
305
+ return {
306
+ ok: false,
307
+ reason: 'source-not-replayable',
308
+ detail: 'The package was installed from a source this plugin will not reinstall.',
309
+ filesMatch: null,
310
+ }
311
+ }
312
+ if (target.source.registryName !== target.targetId) {
313
+ return {
314
+ ok: false,
315
+ reason: 'source-substitution',
316
+ detail: 'The snapshot records a different package name than the target it belongs to.',
317
+ filesMatch: null,
318
+ }
319
+ }
320
+ if (currentFingerprint === null || currentFingerprint === undefined) {
321
+ return {
322
+ ok: false,
323
+ reason: 'not-installed',
324
+ detail: 'The package is no longer present on disk.',
325
+ filesMatch: null,
326
+ }
327
+ }
328
+ // A changed fingerprint is not a refusal. An update *is* a file change, and
329
+ // this snapshot exists precisely so that change can be undone. The mismatch is
330
+ // reported as evidence ("the files were replaced after this snapshot") and the
331
+ // restore reinstalls the recorded version from its recorded registry.
332
+ const recorded = target.fingerprint?.digest ?? null
333
+ const filesMatch = recorded === null ? null : recorded === currentFingerprint.digest
334
+ return { ok: true, reason: null, detail: null, filesMatch }
335
+ }
@@ -0,0 +1,274 @@
1
+ /**
2
+ * Reading a declared install spec as one of the kinds DSH can actually mean.
3
+ *
4
+ * The profile's `package.json` is the only place a declared spec survives, and
5
+ * it is a flat string: `1.2.3`, `^1.2.3`, `file:./x.tgz`, `git+https://...`,
6
+ * `npm:other@1`, `workspace:*`. Everything the panel shows about "where did this
7
+ * come from" and "may I update it" is derived here rather than guessed at the
8
+ * call site, so there is exactly one answer to that question.
9
+ *
10
+ * A wrong answer here is worse than no answer: claiming a `file:` tarball is a
11
+ * registry package would offer the user an update that cannot work. When the
12
+ * shape is not recognised the kind is `unknown` and the panel says so.
13
+ *
14
+ * @module dsh-version-manager/lib/host/spec
15
+ */
16
+
17
+ /** Install kinds this module can prove. */
18
+ export const SPEC_KINDS = Object.freeze([
19
+ 'registry',
20
+ 'git',
21
+ 'file',
22
+ 'link',
23
+ 'tarball',
24
+ 'workspace',
25
+ 'alias',
26
+ 'builtin',
27
+ 'unknown',
28
+ ])
29
+
30
+ /** Kinds an update may ever be offered for. Everything else is read-only. */
31
+ export const UPDATABLE_KINDS = Object.freeze(['registry'])
32
+
33
+ const ARCHIVE = /\.(tgz|tar\.gz|tar|zip)$/i
34
+ const SHORTHAND = /^[\w.-]+\/[\w.-]+(#[^\s]+)?$/
35
+ const GIT_PREFIX = /^(git\+|git@|github:|gitlab:|bitbucket:|ssh:)/i
36
+
37
+ /**
38
+ * Split an npm registry spec into name and range.
39
+ *
40
+ * A scoped name starts with `@`, so the version separator is the first `@`
41
+ * *after* the scope's closing slash. Splitting on the last `@` would also work
42
+ * for `@scope/name@1.2.3`, but not for a name that itself contains no slash, and
43
+ * splitting on the first `@` would mangle every scoped package.
44
+ *
45
+ * @param {string} spec
46
+ * @returns {{ name: string, range: string | null }}
47
+ */
48
+ export function splitRegistrySpec(spec) {
49
+ const at = spec.indexOf('@')
50
+ if (at > 0) return { name: spec.slice(0, at), range: spec.slice(at + 1) || null }
51
+ if (at === 0) {
52
+ const slash = spec.indexOf('/')
53
+ if (slash === -1) return { name: spec, range: null }
54
+ const separator = spec.indexOf('@', slash)
55
+ if (separator === -1) return { name: spec, range: null }
56
+ return { name: spec.slice(0, separator), range: spec.slice(separator + 1) || null }
57
+ }
58
+ return { name: spec, range: null }
59
+ }
60
+
61
+ /**
62
+ * Classify one declared spec.
63
+ *
64
+ * @param {string} spec
65
+ * @param {{ official?: boolean, version?: string | null }} [context]
66
+ * @returns {{ kind: string, name: string | null, range: string | null, detail: string | null }}
67
+ */
68
+ export function classifySpec(spec, context = {}) {
69
+ if (context.official === true) {
70
+ return { kind: 'builtin', name: null, range: null, detail: null }
71
+ }
72
+ if (typeof spec !== 'string' || spec.trim() === '') {
73
+ // No declared spec at all. The row may still have an installed version, but
74
+ // there is nothing to replay and nothing to compare against a registry.
75
+ return { kind: 'unknown', name: null, range: null, detail: null }
76
+ }
77
+
78
+ const value = spec.trim()
79
+
80
+ if (/^file:/i.test(value)) {
81
+ const path = value.slice(5)
82
+ return {
83
+ kind: ARCHIVE.test(path) ? 'tarball' : 'file',
84
+ name: null,
85
+ range: null,
86
+ detail: path,
87
+ }
88
+ }
89
+ if (/^link:/i.test(value)) {
90
+ return { kind: 'link', name: null, range: null, detail: value.slice(5) }
91
+ }
92
+ if (/^workspace:/i.test(value)) {
93
+ return { kind: 'workspace', name: null, range: null, detail: value }
94
+ }
95
+ if (/^npm:/i.test(value)) {
96
+ const inner = splitRegistrySpec(value.slice(4))
97
+ return { kind: 'alias', name: inner.name, range: inner.range, detail: value }
98
+ }
99
+ if (/^https?:\/\//i.test(value)) {
100
+ // A remote archive and a remote repository are different operations and
101
+ // different risks; only the URL shape separates them.
102
+ return {
103
+ kind: ARCHIVE.test(value) || /\/tarball\//i.test(value) ? 'tarball' : 'git',
104
+ name: null,
105
+ range: null,
106
+ detail: value,
107
+ }
108
+ }
109
+ if (GIT_PREFIX.test(value)) {
110
+ return { kind: 'git', name: null, range: null, detail: value }
111
+ }
112
+ if (SHORTHAND.test(value)) {
113
+ return { kind: 'git', name: null, range: null, detail: value }
114
+ }
115
+
116
+ const { name, range } = splitRegistrySpec(value)
117
+ if (name === '' || name.includes(':') || name.includes('/') && !name.startsWith('@')) {
118
+ return { kind: 'unknown', name: null, range: null, detail: value }
119
+ }
120
+ // The host writes a dependency whose key differs from the package name as
121
+ // `<key>@<spec>`, so a Git or file dependency hidden behind a renamed key
122
+ // arrives here looking like a registry range. Classify by the inner spec
123
+ // instead: calling a Git URL a registry package would both mislabel its source
124
+ // and offer an update that cannot work.
125
+ if (range !== null && (range.includes('://') || /^(file|link|git\+|git@|workspace|npm):/i.test(range))) {
126
+ const inner = classifySpec(range, {})
127
+ if (inner.kind !== 'registry' && inner.kind !== 'unknown') {
128
+ return { kind: inner.kind, name, range: inner.range, detail: inner.detail }
129
+ }
130
+ }
131
+ return { kind: 'registry', name, range, detail: null }
132
+ }
133
+
134
+ /**
135
+ * Is this spec an exact version pin (`1.2.3`), as opposed to a range?
136
+ *
137
+ * @param {string | null} range
138
+ * @returns {boolean}
139
+ */
140
+ /**
141
+ * Decide whether the install spec the host reports and the range the profile
142
+ * manifest records describe the same install.
143
+ *
144
+ * The host reports "name@range" while the manifest stores the bare range, so a
145
+ * raw string comparison reports drift on every ordinary install. Compare the
146
+ * range half, and fall back to the two documented spellings.
147
+ *
148
+ * @param {string | null} declaredSpec the spec the host reports
149
+ * @param {string | null} observedRange the range the profile manifest records
150
+ * @param {string} name the package name
151
+ * @returns {boolean}
152
+ */
153
+ export function declaredSpecMatches(declaredSpec, observedRange, name) {
154
+ if (declaredSpec === null || observedRange === null) return false
155
+ if (declaredSpec === observedRange) return true
156
+ if (`${name}@${observedRange}` === declaredSpec) return true
157
+
158
+ // A local install is spelled with whichever separators the writer had at hand:
159
+ // the host reports `file:D:\dir\x.tgz` while the profile manifest that pnpm
160
+ // wrote holds `file:D:/dir/x.tgz`. Those are the same file, so comparing the
161
+ // raw strings would report drift on every local install and teach the user to
162
+ // ignore the one warning that matters.
163
+ const declared = localSpecPath(declaredSpec)
164
+ const observed = localSpecPath(observedRange)
165
+ if (declared !== null && observed !== null) return samePath(declared, observed)
166
+
167
+ return splitRegistrySpec(declaredSpec).range === observedRange
168
+ }
169
+
170
+ /**
171
+ * The filesystem path a `file:`/`link:` spec points at, or null.
172
+ *
173
+ * @param {string} spec
174
+ * @returns {string | null}
175
+ */
176
+ function localSpecPath(spec) {
177
+ const match = /^(?:file|link):(.*)$/i.exec(spec)
178
+ return match === null ? null : match[1]
179
+ }
180
+
181
+ /**
182
+ * Are two spellings of a filesystem path the same file?
183
+ *
184
+ * Only the separators are folded: this compares what two writers recorded, not
185
+ * what the disk currently holds, and touching the disk here would turn a pure
186
+ * comparison into an IO failure mode.
187
+ *
188
+ * @param {string} left
189
+ * @param {string} right
190
+ * @returns {boolean}
191
+ */
192
+ function samePath(left, right) {
193
+ if (left === right) return true
194
+ const fold = value => value.replace(/\\/g, '/').replace(/\/+/g, '/').replace(/\/$/, '')
195
+ return fold(left) === fold(right)
196
+ }
197
+
198
+ /**
199
+ * Turn a declared install spec into the short phrase a row shows.
200
+ *
201
+ * "no declared spec" is a real answer for bundles that ship with DSH or that
202
+ * the host resolves from the installation, so callers must not invent one.
203
+ *
204
+ * @param {{ kind: string, name: string | null, range: string | null, detail: string | null }} parsed
205
+ * @param {string | null} declaredSpec
206
+ * @returns {{ key: string, value: string | null }}
207
+ */
208
+ export function sourceSummary(parsed, declaredSpec) {
209
+ if (declaredSpec === null || declaredSpec === undefined) return { key: 'noDeclaredSpec', value: null }
210
+ if (parsed.kind === 'builtin') return { key: 'builtin', value: null }
211
+ if (parsed.kind === 'registry') return { key: 'registry', value: declaredSpec }
212
+ if (parsed.kind === 'unknown') return { key: 'unknownSource', value: declaredSpec }
213
+ return { key: 'otherSource', value: declaredSpec }
214
+ }
215
+
216
+ export function isExactVersion(range) {
217
+ return typeof range === 'string' && /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(range)
218
+ }
219
+
220
+ /**
221
+ * Is this version a prerelease (`0.2.2-rc.1`)?
222
+ *
223
+ * The default update path must not silently move a user onto a prerelease, so
224
+ * the question is asked of the version string and of nothing else.
225
+ *
226
+ * @param {string | null | undefined} version
227
+ * @returns {boolean}
228
+ */
229
+ export function isPrerelease(version) {
230
+ return typeof version === 'string' && /-\S/.test(version)
231
+ }
232
+
233
+ /**
234
+ * Why a target cannot be updated, in the words the panel will show.
235
+ *
236
+ * This mirrors the host's own gate rather than inventing a second one: a target
237
+ * the host will refuse must be refused here too, and for the same reason.
238
+ *
239
+ * @param {object} row - a bundle row from pluginManager.listBundles()
240
+ * @param {{ kind: string, name: string | null }} parsed
241
+ * @returns {string | null} a reason code, or null when an update is allowed
242
+ */
243
+ export function updateRefusal(row, parsed) {
244
+ if (row.official === true) return 'official-bundle'
245
+ if (row.availability !== 'profile') return 'not-installed-here'
246
+ if (row.installed !== true) return 'not-installed'
247
+ if (row.readOnlyReason !== undefined) {
248
+ return `read-only:${row.readOnlyReason}`
249
+ }
250
+ if (row.source === undefined) return 'no-declared-spec'
251
+ if (parsed.kind === 'alias') {
252
+ // `npm:other@1` pins a different package behind this name. Installing it
253
+ // again would swap what the profile actually depends on.
254
+ return 'alias-substitution'
255
+ }
256
+ if (parsed.kind !== 'registry') {
257
+ return `not-registry:${parsed.kind}`
258
+ }
259
+ if (parsed.name !== row.name) {
260
+ return 'name-substitution'
261
+ }
262
+ if (parsed.range !== null && parsed.range.includes(':')) {
263
+ // The host writes an aliased dependency as `<name>@npm:<other>@<range>`, so
264
+ // the alias hides inside the range rather than at the head of the spec.
265
+ if (/^npm:/i.test(parsed.range)) {
266
+ return 'alias-substitution'
267
+ }
268
+ return 'range-with-scheme'
269
+ }
270
+ if (typeof row.version !== 'string' || row.version === '') {
271
+ return 'no-installed-version'
272
+ }
273
+ return null
274
+ }
package/lib/index.js ADDED
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The host half.
3
+ *
4
+ * DSH loads this through the profile's patch file as a Cordis plugin, so the
5
+ * export shape is the one the loader reads: `name`, `inject`, `apply`. Nothing
6
+ * here writes to the profile on its own — the routes do, and only when a request
7
+ * asked for it.
8
+ *
9
+ * @module dsh-version-manager
10
+ */
11
+
12
+ import { registerRoutes } from './host/routes.js'
13
+
14
+ /** Loader row name. Matches the `id` in cordis.patch.yml, not the package name. */
15
+ export const name = 'version-manager'
16
+
17
+ /**
18
+ * Services this plugin reads. `webServer` is required for the panel to exist at
19
+ * all; `pluginManager` and `connection` are looked up at request time so that a
20
+ * host without them degrades to "unavailable" instead of failing to load.
21
+ */
22
+ export const inject = ['webServer']
23
+
24
+ /**
25
+ * @param {any} ctx
26
+ */
27
+ export function apply(ctx) {
28
+ ctx.inject(['webServer'], (scope) => {
29
+ const webServer = scope.webServer
30
+ if (webServer === undefined || webServer === null || typeof webServer.register !== 'function') {
31
+ // An older host without a webserver simply gets no version panel, and the
32
+ // rest of DSH is untouched.
33
+ return
34
+ }
35
+ const disposers = registerRoutes(ctx, { webServer })
36
+ if (typeof scope.effect === 'function') {
37
+ scope.effect(() => () => {
38
+ for (const dispose of disposers) {
39
+ try {
40
+ dispose()
41
+ } catch {
42
+ // A route already removed during teardown is not an error worth
43
+ // surfacing; the goal is only to leave nothing behind.
44
+ }
45
+ }
46
+ }, 'dsh-version-manager: routes')
47
+ }
48
+ })
49
+ }