@xiangyixie/dsh-superagent 0.12.0 → 0.14.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/lib/doctor.js CHANGED
@@ -1,878 +1,879 @@
1
- /**
2
- * Read-only installation checks for dsh-superagent.
3
- *
4
- * Two real releases failed in the same shape: the package installed cleanly and
5
- * then did nothing. One shipped an `index.js` that imported `lib/memory.js`,
6
- * `lib/notify.js`, and `lib/lock.js` while `package.json` `files` left them out,
7
- * so `npm pack` produced 15 files and the first `import` threw. Another profile
8
- * was left half-unpacked by an interrupted install: `package.json` said 0.9.1
9
- * while only five of eleven `lib` files existed, so the host could not mount
10
- * the plugin and nothing said why.
11
- *
12
- * `doctor` compares the three layers that have to agree — what the code
13
- * imports, what `files` promises, and what is actually on disk — plus the
14
- * profile wiring and the registered tool count. It only reads: no install, no
15
- * mount, no edit to the profile. The one write-free exception is the optional
16
- * registry comparison, which downloads one public tarball to hash it.
17
- *
18
- * @module dsh-superagent/doctor
19
- */
20
- import { exec, execFile } from 'node:child_process'
21
- import { createHash } from 'node:crypto'
22
- import fsp from 'node:fs/promises'
23
- import os from 'node:os'
24
- import path from 'node:path'
25
- import { gunzipSync } from 'node:zlib'
26
-
27
- export const PACKAGE_NAME = '@xiangyixie/dsh-superagent'
28
-
29
- /** Tools this package version must register for the plugin to be complete. */
30
- export const TOOL_NAMES = [
31
- 'superagent_start',
32
- 'superagent_status',
33
- 'superagent_list',
34
- 'superagent_cancel',
35
- 'superagent_resume',
36
- 'superagent_followup',
37
- 'superagent_inject',
38
- 'superagent_answer',
39
- 'superagent_memory',
40
- 'superagent_template',
41
- 'superagent_audit',
42
- ]
43
-
44
- /** Files npm always includes, whether or not `files` lists them. */
45
- const ALWAYS_PACKED = new Set(['package.json'])
46
-
47
- /**
48
- * Relative import specifiers: `import x from './y.js'`, `export … from './y.js'`,
49
- * and `import './y.js'`. Only specifiers that start with `.` are package files;
50
- * bare names are built-ins or dependencies and are not ours to ship.
51
- */
52
- const RELATIVE_IMPORT = /\b(?:from\s*|import\s*\(\s*|import\s*)['"](\.[^'"]+)['"]/g
53
-
54
- export function normalizeRel(value) {
55
- return String(value).replace(/\\/g, '/').replace(/^\.\//, '')
56
- }
57
-
58
- /**
59
- * Remove comments while keeping string literals intact. A doc comment that
60
- * mentions an import path must not become a dependency of the package.
61
- */
62
- export function stripComments(source) {
63
- const text = String(source)
64
- let out = ''
65
- let state = null
66
- for (let index = 0; index < text.length; index++) {
67
- const char = text[index]
68
- const next = text[index + 1]
69
- if (state === null) {
70
- if (char === '/' && next === '/') {
71
- state = 'line'
72
- index += 1
73
- } else if (char === '/' && next === '*') {
74
- state = 'block'
75
- index += 1
76
- } else {
77
- if (char === "'" || char === '"' || char === '`') state = char
78
- out += char
79
- }
80
- } else if (state === 'line') {
81
- if (char === '\n') {
82
- state = null
83
- out += char
84
- }
85
- } else if (state === 'block') {
86
- if (char === '*' && next === '/') {
87
- state = null
88
- index += 1
89
- } else if (char === '\n') {
90
- out += char
91
- }
92
- } else {
93
- out += char
94
- if (char === '\\') {
95
- if (index + 1 < text.length) out += text[++index]
96
- } else if (char === state) {
97
- state = null
98
- }
99
- }
100
- }
101
- return out
102
- }
103
-
104
- /** Every relative specifier a source file mentions, in order, without duplicates. */
105
- export function scanRelativeImports(source) {
106
- const found = new Set()
107
- for (const match of stripComments(source).matchAll(RELATIVE_IMPORT)) {
108
- if (match[1].startsWith('..') || match[1].startsWith('./')) found.add(match[1])
109
- }
110
- return [...found]
111
- }
112
-
113
- /**
114
- * Tool names a plugin entry point registers.
115
- *
116
- * The registration call is split at `ctx.tools.register(` and the first `name:`
117
- * in each chunk is the tool. That survives reformatting far better than one
118
- * giant regular expression, and it still counts a registration whose body the
119
- * parser would reject.
120
- */
121
- export function readRegisteredTools(source) {
122
- const names = []
123
- for (const chunk of String(source).split('ctx.tools.register(').slice(1)) {
124
- const match = /name:\s*['"]([^'"]+)['"]/.exec(chunk)
125
- if (match) names.push(match[1])
126
- }
127
- return names
128
- }
129
-
130
- function parseVersion(value) {
131
- const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(value ?? '').trim())
132
- return match ? { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]) } : null
133
- }
134
-
135
- function compareVersions(left, right) {
136
- for (const key of ['major', 'minor', 'patch']) {
137
- if (left[key] !== right[key]) return left[key] < right[key] ? -1 : 1
138
- }
139
- return 0
140
- }
141
-
142
- function satisfiesToken(token, version) {
143
- const match = /^(>=|<=|>|<|=|\^|~)?\s*(\d+)(?:\.(\d+))?(?:\.(\d+))?$/.exec(token)
144
- if (!match) return false
145
- const target = {
146
- major: Number(match[2]),
147
- minor: Number(match[3] ?? 0),
148
- patch: Number(match[4] ?? 0),
149
- }
150
- const relation = compareVersions(version, target)
151
- switch (match[1] ?? '=') {
152
- case '>=': return relation >= 0
153
- case '>': return relation > 0
154
- case '<=': return relation <= 0
155
- case '<': return relation < 0
156
- case '=': return relation === 0
157
- case '^': {
158
- if (relation < 0) return false
159
- const ceiling = target.major > 0
160
- ? { major: target.major + 1, minor: 0, patch: 0 }
161
- : { major: 0, minor: target.minor + 1, patch: 0 }
162
- return compareVersions(version, ceiling) < 0
163
- }
164
- case '~': {
165
- if (relation < 0) return false
166
- return compareVersions(version, { major: target.major, minor: target.minor + 1, patch: 0 }) < 0
167
- }
168
- default: return false
169
- }
170
- }
171
-
172
- /**
173
- * Test a plain semver range against a version. Supports `||`, space-separated
174
- * conjunctions, and the comparators an `engines` field actually uses. Anything
175
- * it cannot parse fails closed, because "unknown range" must not read as "fine".
176
- */
177
- export function satisfiesRange(range, version) {
178
- const parsed = parseVersion(version)
179
- if (!parsed) return false
180
- const text = String(range ?? '').trim()
181
- if (!text || text === '*') return true
182
- return text.split('||').some(part => {
183
- const tokens = part.trim().split(/\s+/).filter(Boolean)
184
- return tokens.length === 0 || tokens.every(token => satisfiesToken(token, parsed))
185
- })
186
- }
187
-
188
- async function exists(target) {
189
- try {
190
- await fsp.access(target)
191
- return true
192
- } catch {
193
- return false
194
- }
195
- }
196
-
197
- export async function readPackageJson(packageRoot) {
198
- const file = path.join(packageRoot, 'package.json')
199
- let text
200
- try {
201
- text = await fsp.readFile(file, 'utf8')
202
- } catch (error) {
203
- throw new Error(`cannot read ${file}: ${error?.message ?? error}`)
204
- }
205
- try {
206
- return JSON.parse(text)
207
- } catch (error) {
208
- throw new Error(`${file} is not valid JSON: ${error?.message ?? error}`)
209
- }
210
- }
211
-
212
- function exportTargets(exportsField) {
213
- const targets = []
214
- const walk = value => {
215
- if (typeof value === 'string') targets.push(value)
216
- else if (Array.isArray(value)) value.forEach(walk)
217
- else if (value && typeof value === 'object') Object.values(value).forEach(walk)
218
- }
219
- walk(exportsField)
220
- return targets
221
- }
222
-
223
- /** Resolve `./x.js` written in `fromRel` to a repo-relative path that exists. */
224
- async function resolveLocalFile(packageRoot, fromRel, specifier) {
225
- const joined = path.posix.normalize(path.posix.join(path.posix.dirname(fromRel), specifier))
226
- if (joined.startsWith('..')) return null
227
- const candidates = [joined]
228
- if (!path.posix.extname(joined)) candidates.push(`${joined}.js`, `${joined}/index.js`)
229
- for (const candidate of candidates) {
230
- if (await exists(path.join(packageRoot, candidate))) return candidate
231
- }
232
- return joined
233
- }
234
-
235
- /**
236
- * Files the package cannot run without: entry points plus everything they
237
- * import, transitively. `package.json` is included because `index.js` reads its
238
- * version, but npm always packs it, so it needs no `files` entry.
239
- */
240
- export async function requiredFiles(packageRoot) {
241
- const pkg = await readPackageJson(packageRoot)
242
- const roots = new Set()
243
- const addRoot = value => {
244
- if (typeof value === 'string' && value.trim()) roots.add(normalizeRel(value.trim()))
245
- }
246
- addRoot(pkg.main)
247
- for (const value of Object.values(pkg.bin ?? {})) addRoot(value)
248
- exportTargets(pkg.exports).forEach(addRoot)
249
- addRoot(pkg.dsh?.bundle?.patch)
250
- if (roots.size === 0) addRoot('lib/index.js')
251
-
252
- const required = new Set()
253
- const queue = [...roots]
254
- while (queue.length > 0) {
255
- const rel = queue.shift()
256
- if (required.has(rel)) continue
257
- required.add(rel)
258
- if (!rel.endsWith('.js')) continue
259
- let source
260
- try {
261
- source = await fsp.readFile(path.join(packageRoot, rel), 'utf8')
262
- } catch {
263
- continue
264
- }
265
- for (const specifier of scanRelativeImports(source)) {
266
- const resolved = await resolveLocalFile(packageRoot, rel, specifier)
267
- if (resolved && !required.has(resolved)) queue.push(resolved)
268
- }
269
- }
270
- return [...required].sort()
271
- }
272
-
273
- function matchesFilesEntry(rel, entry) {
274
- const pattern = normalizeRel(entry).replace(/\/+$/, '')
275
- if (!pattern) return false
276
- if (!pattern.includes('*')) return rel === pattern || rel.startsWith(`${pattern}/`)
277
- const escaped = pattern
278
- .split('*')
279
- .map(part => part.replace(/[.+^${}()|[\]\\]/g, '\\$&'))
280
- .join('[^/]*')
281
- return new RegExp(`^${escaped}$`).test(rel) || new RegExp(`^${escaped}/`).test(rel)
282
- }
283
-
284
- /**
285
- * Compare one package directory's imports, `files` whitelist, and disk contents.
286
- * @param {string} packageRoot - absolute package directory.
287
- */
288
- export async function auditLayout(packageRoot) {
289
- const pkg = await readPackageJson(packageRoot)
290
- const required = await requiredFiles(packageRoot)
291
- const declared = Array.isArray(pkg.files) ? pkg.files.map(normalizeRel) : []
292
-
293
- const missingFromDisk = []
294
- for (const rel of required) {
295
- if (!(await exists(path.join(packageRoot, rel)))) missingFromDisk.push(rel)
296
- }
297
- const uncovered = required.filter(rel => !ALWAYS_PACKED.has(rel)
298
- && !declared.some(entry => matchesFilesEntry(rel, entry)))
299
-
300
- const missingDeclared = []
301
- for (const entry of declared) {
302
- if (entry.includes('*')) continue
303
- if (!(await exists(path.join(packageRoot, entry)))) missingDeclared.push(entry)
304
- }
305
-
306
- let libOnDisk = 0
307
- try {
308
- const entries = await fsp.readdir(path.join(packageRoot, 'lib'), { withFileTypes: true })
309
- libOnDisk = entries.filter(entry => entry.isFile() && entry.name.endsWith('.js')).length
310
- } catch {
311
- libOnDisk = 0
312
- }
313
- const libDeclared = declared.filter(entry => /^lib\/[^/*]+\.js$/.test(entry)).length
314
-
315
- return {
316
- packageRoot,
317
- name: pkg.name ?? null,
318
- version: pkg.version ?? null,
319
- engines: pkg.engines ?? {},
320
- declared,
321
- required,
322
- missingFromDisk,
323
- uncovered,
324
- missingDeclared,
325
- libOnDisk,
326
- libDeclared,
327
- }
328
- }
329
-
330
- /** Paths of everything `npm pack` would include, via a dry run (no tarball). */
331
- export function packFileList(packageRoot) {
332
- const args = 'pack --dry-run --json --ignore-scripts'
333
- const options = { cwd: packageRoot, timeout: 120_000, maxBuffer: 16 * 1024 * 1024 }
334
- return new Promise((resolve, reject) => {
335
- const done = (error, stdout, stderr) => {
336
- if (error) {
337
- reject(new Error(`npm pack --dry-run failed: ${(stderr || error.message || '').trim()}`))
338
- return
339
- }
340
- try {
341
- const start = stdout.indexOf('[')
342
- const parsed = JSON.parse(start >= 0 ? stdout.slice(start) : stdout)
343
- resolve((parsed[0]?.files ?? []).map(file => normalizeRel(file.path)))
344
- } catch (parseError) {
345
- reject(new Error(`cannot parse npm pack JSON: ${parseError.message}`))
346
- }
347
- }
348
- // npm is a .cmd shim on Windows, which needs a shell; the command string is
349
- // composed only of literals, so there is nothing to escape.
350
- if (process.platform === 'win32') exec(`npm ${args}`, options, done)
351
- else execFile('npm', args.split(' '), options, done)
352
- })
353
- }
354
-
355
- /**
356
- * The CI guard: every file the code imports must appear in the tarball, and
357
- * every plain `files` entry must actually be packed. A `files` entry npm cannot
358
- * find is silently skipped, which is how an import ships a promise instead of a
359
- * module.
360
- * @param {{ packageRoot: string, packed: string[] }} input - dry-run file list.
361
- */
362
- export async function auditPackedFiles({ packageRoot, packed }) {
363
- const layout = await auditLayout(packageRoot)
364
- const shipped = new Set(packed.map(normalizeRel))
365
- const missing = layout.required.filter(rel => !ALWAYS_PACKED.has(rel) && !shipped.has(rel))
366
- const notPacked = layout.declared.filter(entry => !entry.includes('*')
367
- && !ALWAYS_PACKED.has(entry)
368
- && !shipped.has(entry))
369
- return { ...layout, packed: [...shipped], missing, notPacked }
370
- }
371
-
372
- function readTarString(header, start, length) {
373
- return header.toString('utf8', start, start + length).replace(/\0.*$/s, '').trimEnd()
374
- }
375
-
376
- /**
377
- * Minimal ustar reader: only what a published npm tarball contains. Returns
378
- * regular files with their bytes, so hashes can be compared without unpacking
379
- * to disk.
380
- */
381
- export function readTarEntries(buffer) {
382
- const data = buffer[0] === 0x1f && buffer[1] === 0x8b ? gunzipSync(buffer) : buffer
383
- const entries = []
384
- let offset = 0
385
- while (offset + 512 <= data.length) {
386
- const header = data.subarray(offset, offset + 512)
387
- if (header.every(byte => byte === 0)) break
388
- const name = readTarString(header, 0, 100)
389
- const prefix = readTarString(header, 345, 155)
390
- const size = Number.parseInt(readTarString(header, 124, 12), 8) || 0
391
- const type = String.fromCharCode(header[156] || 48)
392
- offset += 512
393
- const fullName = normalizeRel(prefix ? `${prefix}/${name}` : name)
394
- if (type === '0' || type === '\0' || type === '7') {
395
- entries.push({ name: fullName.replace(/^package\//, ''), data: data.subarray(offset, offset + size) })
396
- }
397
- offset += Math.ceil(size / 512) * 512
398
- }
399
- return entries
400
- }
401
-
402
- function sha256(data) {
403
- return createHash('sha256').update(data).digest('hex')
404
- }
405
-
406
- /**
407
- * Compare the files of the installed copy with the published tarball for the
408
- * same version. Networks are optional: an unreachable registry degrades this
409
- * check to a warning with the command that would confirm it by hand.
410
- * @param {object} input - package directory, fetch implementation, timeout.
411
- */
412
- export async function auditRegistry({ packageRoot, fetchImpl = globalThis.fetch, timeoutMs = 8000, profileName = null } = {}) {
413
- const pkg = await readPackageJson(packageRoot)
414
- const name = pkg.name ?? PACKAGE_NAME
415
- const version = pkg.version ?? '0.0.0'
416
- const registry = String(pkg.publishConfig?.registry ?? 'https://registry.npmjs.org').replace(/\/+$/, '')
417
- const metadataUrl = `${registry}/${name.replace('/', '%2F')}/${version}`
418
- const offlineFix = `npm view ${name}@${version} dist.tarball`
419
-
420
- if (typeof fetchImpl !== 'function') {
421
- return { status: 'warn', detail: ['no fetch implementation; registry comparison skipped'], fix: offlineFix }
422
- }
423
- try {
424
- const metaResponse = await fetchImpl(metadataUrl, {
425
- headers: { accept: 'application/json' },
426
- signal: AbortSignal.timeout(timeoutMs),
427
- })
428
- if (!metaResponse.ok) throw new Error(`registry returned HTTP ${metaResponse.status}`)
429
- const meta = await metaResponse.json()
430
- const tarballUrl = meta?.dist?.tarball
431
- if (!tarballUrl) throw new Error('registry metadata has no dist.tarball')
432
-
433
- const tarResponse = await fetchImpl(tarballUrl, { signal: AbortSignal.timeout(timeoutMs) })
434
- if (!tarResponse.ok) throw new Error(`tarball returned HTTP ${tarResponse.status}`)
435
- const tarball = Buffer.from(await tarResponse.arrayBuffer())
436
- const published = new Map(readTarEntries(tarball).map(entry => [entry.name, sha256(entry.data)]))
437
-
438
- const missing = []
439
- const different = []
440
- let compared = 0
441
- for (const [file, digest] of published) {
442
- // package.json is rewritten by tooling on some installs; the version field
443
- // is checked by the layout audit instead of by byte equality.
444
- if (file === 'package.json') continue
445
- let local
446
- try {
447
- local = await fsp.readFile(path.join(packageRoot, file))
448
- } catch {
449
- missing.push(file)
450
- continue
451
- }
452
- compared += 1
453
- if (sha256(local) !== digest) different.push(file)
454
- }
455
-
456
- const extra = []
457
- for (const file of await listFilesRecursive(packageRoot)) {
458
- if (file === 'package.json') continue
459
- if (!published.has(file)) extra.push(file)
460
- }
461
-
462
- if (missing.length > 0 || different.length > 0) {
463
- const detail = []
464
- if (missing.length > 0) {
465
- detail.push(`${missing.length} published file(s) are missing from the installed copy:`)
466
- detail.push(...missing.slice(0, 8).map(file => ` ${file}`))
467
- }
468
- if (different.length > 0) {
469
- detail.push(`${different.length} file(s) differ from ${name}@${version}:`)
470
- detail.push(...different.slice(0, 8).map(file => ` ${file}`))
471
- }
472
- return {
473
- status: 'fail',
474
- detail,
475
- fix: 'this copy is not the published artifact; reinstall it from the registry:\n'
476
- + reinstallCommand(profileName, version)
477
- + '\n# if it came from a local tarball, rebuild that tarball and reinstall it instead',
478
- }
479
- }
480
- const detail = [`${compared} file(s) match ${name}@${version} by sha256`]
481
- if (extra.length > 0) detail.push(`${extra.length} local file(s) are not in the published tarball: ${extra.slice(0, 5).join(', ')}`)
482
- return { status: extra.length > 0 ? 'warn' : 'pass', detail }
483
- } catch (error) {
484
- return {
485
- status: 'warn',
486
- detail: [`registry comparison skipped: ${error?.message ?? error}`, 'offline is fine; the other checks still ran'],
487
- fix: offlineFix,
488
- }
489
- }
490
- }
491
-
492
- async function listFilesRecursive(root) {
493
- const found = []
494
- const walk = async dir => {
495
- let entries
496
- try {
497
- entries = await fsp.readdir(dir, { withFileTypes: true })
498
- } catch {
499
- return
500
- }
501
- for (const entry of entries) {
502
- const abs = path.join(dir, entry.name)
503
- if (entry.isDirectory()) await walk(abs)
504
- else if (entry.isFile()) found.push(normalizeRel(path.relative(root, abs)))
505
- }
506
- }
507
- await walk(root)
508
- return found.sort()
509
- }
510
-
511
- /** Resolve `--profile web` to `<DSH_HOME>/profiles/web`; a path is used as-is. */
512
- export function resolveProfileDir(profile, dshHome) {
513
- if (!profile) return null
514
- if (profile === '.' || profile === '..' || profile.includes('/') || profile.includes('\\')) {
515
- return path.resolve(profile)
516
- }
517
- return path.join(dshHome, 'profiles', profile)
518
- }
519
-
520
- /**
521
- * Infer the profile from a package path such as
522
- * `<DSH_HOME>/profiles/web/node_modules/@xiangyixie/dsh-superagent`.
523
- */
524
- export function inferProfileDir(packageRoot) {
525
- const parts = path.resolve(packageRoot).split(path.sep)
526
- const index = parts.lastIndexOf('profiles')
527
- if (index < 0 || index + 1 >= parts.length) return null
528
- const name = parts[index + 1]
529
- if (!name || name === 'node_modules') return null
530
- return parts.slice(0, index + 2).join(path.sep)
531
- }
532
-
533
- function reinstallCommand(profileName, version) {
534
- return `dsh plugin --profile ${profileName ?? '<profile>'} add ${PACKAGE_NAME}@${version ?? '<version>'}`
535
- }
536
-
537
- function cleanCopyCommand(packageDir) {
538
- return process.platform === 'win32'
539
- ? `Remove-Item -Recurse -Force "${packageDir}"`
540
- : `rm -rf "${packageDir}"`
541
- }
542
-
543
- function check(id, title, status, detail = [], fix = null) {
544
- return { id, title, status, detail, fix }
545
- }
546
-
547
- function checkNodeEngine(layout, nodeVersion) {
548
- const range = layout.engines?.node
549
- if (!range) {
550
- return check('node-engine', 'Node version', 'warn', ['package.json declares no engines.node, so no minimum is enforced'])
551
- }
552
- if (satisfiesRange(range, nodeVersion)) {
553
- return check('node-engine', 'Node version', 'pass', [`v${nodeVersion} satisfies "${range}"`])
554
- }
555
- return check('node-engine', 'Node version', 'fail', [
556
- `installed Node is v${nodeVersion}, but package.json requires "${range}"`,
557
- 'the host and this package are running on an unsupported Node; imports can fail at startup',
558
- ], `install Node ${range} (or newer) and run the host on it:\nnode --version`)
559
- }
560
-
561
- function checkFilesCoverage(layout, { profileName }) {
562
- const detail = []
563
- if (layout.uncovered.length > 0) {
564
- detail.push(`${layout.uncovered.length} imported file(s) are not matched by package.json "files":`)
565
- detail.push(...layout.uncovered.slice(0, 8).map(file => ` ${file}`))
566
- if (layout.uncovered.length > 8) detail.push(` ... and ${layout.uncovered.length - 8} more`)
567
- }
568
- if (layout.missingFromDisk.length > 0) {
569
- detail.push(`${layout.missingFromDisk.length} imported file(s) do not exist on disk:`)
570
- detail.push(...layout.missingFromDisk.slice(0, 8).map(file => ` ${file}`))
571
- }
572
- if (detail.length === 0) {
573
- return check('package-files', 'Package files', 'pass', [
574
- `${layout.required.length} file(s) reachable from the entry points; all are shipped by "files"`,
575
- ])
576
- }
577
- const fixLines = []
578
- if (layout.uncovered.length > 0) {
579
- fixLines.push('add the missing entry to "files" in package.json, then pack and reinstall:')
580
- fixLines.push(...layout.uncovered.slice(0, 8).map(file => ` "${file}"`))
581
- fixLines.push('npm pack --dry-run --json')
582
- }
583
- if (layout.missingFromDisk.length > 0) {
584
- fixLines.push('restore the file from git, or reinstall a complete copy:')
585
- fixLines.push(reinstallCommand(profileName, layout.version))
586
- }
587
- return check('package-files', 'Package files', 'fail', detail, fixLines.join('\n'))
588
- }
589
-
590
- function checkInstalledCopy(layout, { profileName }) {
591
- if (layout.missingDeclared.length === 0 && layout.libDeclared <= layout.libOnDisk) {
592
- return check('installed-copy', 'Installed copy', 'pass', [
593
- `package.json ${layout.version ?? '(no version)'} declares ${layout.declared.length} packed file(s); `
594
- + `${layout.libOnDisk} lib file(s) on disk`,
595
- ])
596
- }
597
- const detail = [
598
- `package.json says version ${layout.version ?? '(none)'} and "files" lists ${layout.libDeclared} lib file(s), `
599
- + `but only ${layout.libOnDisk} are on disk`,
600
- ]
601
- if (layout.missingDeclared.length > 0) {
602
- detail.push(`${layout.missingDeclared.length} declared file(s) are absent:`)
603
- detail.push(...layout.missingDeclared.slice(0, 8).map(file => ` ${file}`))
604
- if (layout.missingDeclared.length > 8) detail.push(` ... and ${layout.missingDeclared.length - 8} more`)
605
- }
606
- detail.push('this is what an interrupted install leaves behind: package.json is complete, the unpacked tree is not')
607
- return check('installed-copy', 'Installed copy', 'fail', detail, [
608
- 'remove the partial copy and install it again:',
609
- cleanCopyCommand(layout.packageRoot),
610
- reinstallCommand(profileName, layout.version),
611
- ].join('\n'))
612
- }
613
-
614
- function checkSyntax(packageRoot, required, { profileName, version }) {
615
- return new Promise(resolve => {
616
- const files = required.filter(file => file.endsWith('.js'))
617
- const broken = []
618
- const verify = index => {
619
- if (index >= files.length) {
620
- if (broken.length === 0) {
621
- resolve(check('syntax', 'File syntax', 'pass', [`${files.length} shipped JavaScript file(s) parse`]))
622
- return
623
- }
624
- resolve(check('syntax', 'File syntax', 'fail', [
625
- `${broken.length} shipped file(s) cannot be parsed (truncated by a partial unpack or a broken build):`,
626
- ...broken.map(item => ` ${item.file}: ${item.reason}`),
627
- ], `reinstall a complete copy:\n${reinstallCommand(profileName, version)}`))
628
- return
629
- }
630
- const file = files[index]
631
- execFile(process.execPath, ['--check', path.join(packageRoot, file)], { timeout: 20_000 }, (error, _stdout, stderr) => {
632
- if (error) {
633
- const reason = String(stderr || error.message).split('\n').find(line => line.trim()) ?? 'parse error'
634
- broken.push({ file, reason: reason.replace(/^.*?Error:\s*/, '').trim() })
635
- }
636
- verify(index + 1)
637
- })
638
- }
639
- verify(0)
640
- })
641
- }
642
-
643
- async function checkTools(packageDir, expected, { profileName, version }) {
644
- const entry = path.join(packageDir, 'lib', 'index.js')
645
- let source
646
- try {
647
- source = await fsp.readFile(entry, 'utf8')
648
- } catch {
649
- return check('tools', 'Registered tools', 'fail', [
650
- `cannot read ${entry}`,
651
- 'without the entry point the host mounts no tools at all',
652
- ], `reinstall a complete copy:\n${reinstallCommand(profileName, version)}`)
653
- }
654
- const names = readRegisteredTools(source)
655
- const missing = expected.filter(name => !names.includes(name))
656
- const extra = names.filter(name => !expected.includes(name))
657
- if (missing.length === 0 && extra.length === 0) {
658
- return check('tools', 'Registered tools', 'pass', [`${names.length}/${expected.length} expected tools are registered`])
659
- }
660
- const detail = [`registered ${names.length} of ${expected.length} expected tools`]
661
- if (missing.length > 0) detail.push(`missing: ${missing.join(', ')}`)
662
- if (extra.length > 0) detail.push(`unexpected: ${extra.join(', ')}`)
663
- return check('tools', 'Registered tools', 'fail', detail, [
664
- 'this copy registers a different tool set than the version claims; reinstall it:',
665
- reinstallCommand(profileName, version),
666
- ].join('\n'))
667
- }
668
-
669
- async function checkPatchFile(packageDir, pkg, { profileName }) {
670
- const patchRel = pkg?.dsh?.bundle?.patch
671
- if (typeof patchRel !== 'string' || !patchRel.trim()) {
672
- return check('patch', 'Bundle patch', 'fail', [
673
- 'package.json has no dsh.bundle.patch, so the host has no row to mount',
674
- ], `reinstall a complete copy:\n${reinstallCommand(profileName, pkg?.version)}`)
675
- }
676
- const file = path.join(packageDir, normalizeRel(patchRel))
677
- let text
678
- try {
679
- text = await fsp.readFile(file, 'utf8')
680
- } catch {
681
- return check('patch', 'Bundle patch', 'fail', [
682
- `package.json points at ${patchRel}, but that file is not in the package`,
683
- ], `reinstall a complete copy:\n${reinstallCommand(profileName, pkg?.version)}`)
684
- }
685
- const namesPackage = text.includes(pkg?.name ?? PACKAGE_NAME)
686
- const inserts = /(^|\n)\s*-\s*insert:/.test(text)
687
- if (!inserts || !namesPackage) {
688
- return check('patch', 'Bundle patch', 'fail', [
689
- `${patchRel} does not insert a row for ${pkg?.name ?? PACKAGE_NAME}`,
690
- 'without the row the plugin is installed but never mounted',
691
- ], `reinstall a complete copy:\n${reinstallCommand(profileName, pkg?.version)}`)
692
- }
693
- return check('patch', 'Bundle patch', 'pass', [`${patchRel} inserts the plugin row at profile scope`])
694
- }
695
-
696
- async function checkProfile(profileDir, profileName) {
697
- if (!(await exists(profileDir))) {
698
- return check('profile', 'DSH profile', 'fail', [
699
- `no profile at ${profileDir}`,
700
- 'nothing is installed there, so no superagent tool can exist in it',
701
- ], `${reinstallCommand(profileName, null)}\n# if DSH_HOME points elsewhere, pass the full path: --profile "<path>"`)
702
- }
703
- const detail = []
704
- try {
705
- await readPackageJson(profileDir)
706
- } catch (error) {
707
- return check('profile', 'DSH profile', 'fail', [String(error.message)], [
708
- 'make the profile readable, then reinstall the plugin:',
709
- reinstallCommand(profileName, null),
710
- ].join('\n'))
711
- }
712
- const hasNodeModules = await exists(path.join(profileDir, 'node_modules'))
713
- const hasRoot = await exists(path.join(profileDir, 'cordis.yml'))
714
- if (!hasNodeModules) {
715
- detail.push('node_modules is missing, so no plugin copy is installed')
716
- }
717
- if (!hasRoot) {
718
- detail.push('cordis.yml is missing; the host composes an empty root, which usually still works')
719
- }
720
- if (!hasNodeModules) {
721
- return check('profile', 'DSH profile', 'fail', detail, [
722
- 'install the plugin into this profile:',
723
- reinstallCommand(profileName, null),
724
- ].join('\n'))
725
- }
726
- return check('profile', 'DSH profile', hasRoot ? 'pass' : 'warn', detail.length > 0
727
- ? detail
728
- : [`${profileDir} has package.json, cordis.yml, and node_modules`])
729
- }
730
-
731
- async function checkBundle(profileDir, packageName, profileName, version) {
732
- try {
733
- const pkg = await readPackageJson(profileDir)
734
- const bundles = pkg?.dsh?.profile?.bundles
735
- if (Array.isArray(bundles) && bundles.includes(packageName)) {
736
- return check('bundle', 'Profile registration', 'pass', [
737
- `dsh.profile.bundles includes ${packageName}`,
738
- ])
739
- }
740
- return check('bundle', 'Profile registration', 'fail', [
741
- `${packageName} is not in dsh.profile.bundles, so its cordis.patch.yml is never loaded`,
742
- 'the installed files are fine; the profile simply does not mount them',
743
- ], `${reinstallCommand(profileName, version)}\n# then confirm the row appears:\ndsh --profile ${profileName ?? '<profile>'} --dump-config`)
744
- } catch (error) {
745
- return check('bundle', 'Profile registration', 'fail', [String(error.message)])
746
- }
747
- }
748
-
749
- async function checkVersionDrift(packageRoot, targetDir, profileName) {
750
- if (path.resolve(packageRoot) === path.resolve(targetDir)) return null
751
- try {
752
- const checkout = await readPackageJson(packageRoot)
753
- const installed = await readPackageJson(targetDir)
754
- if (checkout.version === installed.version) return null
755
- return check('version', 'Version match', 'warn', [
756
- `installed copy is ${installed.version}, this checkout is ${checkout.version}`,
757
- `${targetDir} did not come from this source tree; reinstall it before trusting a fix here`,
758
- ], reinstallCommand(profileName, checkout.version))
759
- } catch {
760
- return null
761
- }
762
- }
763
-
764
- /**
765
- * Run every check and return structured results. Rendering is separate so the
766
- * CLI and the tests see the same verdicts.
767
- * @param {object} [options] - paths, offline switch, and injectable fetch.
768
- */
769
- export async function runDoctor(options = {}) {
770
- const packageRoot = path.resolve(options.packageRoot ?? process.cwd())
771
- const dshHome = options.dshHome ?? process.env.DSH_HOME?.trim() ?? path.join(os.homedir(), '.dsh')
772
- const profileDir = options.profile === undefined
773
- ? inferProfileDir(packageRoot)
774
- : resolveProfileDir(options.profile, dshHome)
775
- const profileName = profileDir ? path.basename(profileDir) : null
776
- const nodeVersion = options.nodeVersion ?? process.versions.node
777
-
778
- let pkg
779
- try {
780
- pkg = await readPackageJson(packageRoot)
781
- } catch (error) {
782
- return {
783
- packageRoot,
784
- profileDir,
785
- profileName,
786
- targetDir: packageRoot,
787
- version: null,
788
- nodeVersion,
789
- ok: false,
790
- checks: [check('package', 'Package', 'fail', [String(error.message)], 'run this command from an installed copy or pass --package <dir>')],
791
- }
792
- }
793
- const packageName = pkg.name ?? PACKAGE_NAME
794
- const candidate = profileDir
795
- ? path.join(profileDir, 'node_modules', ...packageName.split('/'))
796
- : null
797
- const installedDir = candidate && await exists(candidate) ? candidate : null
798
- const targetDir = installedDir ?? packageRoot
799
- const targetPkg = installedDir ? await readPackageJson(installedDir).catch(() => pkg) : pkg
800
-
801
- const layout = await auditLayout(targetDir)
802
- const checks = []
803
- checks.push(checkNodeEngine(layout, nodeVersion))
804
- checks.push(checkFilesCoverage(layout, { profileName }))
805
- checks.push(checkInstalledCopy(layout, { profileName }))
806
- checks.push(await checkSyntax(targetDir, layout.required, { profileName, version: targetPkg.version }))
807
- if (options.online === false) {
808
- checks.push(check('registry', 'Registry match', 'warn', ['registry comparison skipped (--offline)'], `npm view ${packageName}@${targetPkg.version} dist.tarball`))
809
- } else {
810
- const registry = await auditRegistry({
811
- packageRoot: targetDir,
812
- fetchImpl: options.fetchImpl,
813
- timeoutMs: options.registryTimeoutMs,
814
- profileName,
815
- })
816
- checks.push(check('registry', 'Registry match', registry.status, registry.detail, registry.fix ?? null))
817
- }
818
- checks.push(await checkTools(targetDir, options.expectedTools ?? TOOL_NAMES, { profileName, version: targetPkg.version }))
819
- checks.push(await checkPatchFile(targetDir, targetPkg, { profileName }))
820
- if (profileDir) {
821
- checks.push(await checkProfile(profileDir, profileName))
822
- checks.push(await checkBundle(profileDir, packageName, profileName, targetPkg.version))
823
- const drift = await checkVersionDrift(packageRoot, targetDir, profileName)
824
- if (drift) checks.push(drift)
825
- } else {
826
- checks.push(check('profile', 'DSH profile', 'warn', [
827
- 'no profile given, so profile wiring was not checked',
828
- 'run again with --profile <name> (for example: --profile web)',
829
- ]))
830
- }
831
- const counts = { pass: 0, warn: 0, fail: 0 }
832
- for (const item of checks) counts[item.status] += 1
833
- return {
834
- packageRoot,
835
- profileDir,
836
- profileName,
837
- targetDir,
838
- version: targetPkg.version ?? null,
839
- nodeVersion,
840
- checks,
841
- counts,
842
- ok: counts.fail === 0,
843
- }
844
- }
845
-
846
- const STATUS_COLOR = { pass: '32', warn: '33', fail: '31' }
847
- const STATUS_LABEL = { pass: 'PASS', warn: 'WARN', fail: 'FAIL' }
848
-
849
- /**
850
- * Human report: one block per check, then the exact commands that fix what is
851
- * broken. Commands sit on their own lines so they can be copied verbatim.
852
- */
853
- export function renderReport(result, { color = false } = {}) {
854
- const paint = (code, text) => (color ? `\x1b[${code}m${text}\x1b[0m` : text)
855
- const lines = [
856
- `dsh-superagent doctor${result.version ? ` ${result.version}` : ''}`,
857
- `node v${result.nodeVersion} · ${process.platform}`,
858
- `package: ${result.targetDir}`,
859
- result.profileDir
860
- ? `profile: ${result.profileDir}`
861
- : 'profile: not specified (pass --profile <name> to check a DSH profile)',
862
- '',
863
- ]
864
- for (const item of result.checks) {
865
- lines.push(`${paint(STATUS_COLOR[item.status], `[${STATUS_LABEL[item.status]}]`)} ${item.title}`)
866
- for (const detail of item.detail ?? []) lines.push(` ${detail}`)
867
- if (item.fix) {
868
- lines.push(' fix:')
869
- for (const fixLine of item.fix.split('\n')) lines.push(` ${fixLine}`)
870
- }
871
- }
872
- const { pass, warn, fail } = result.counts
873
- lines.push('', `${fail} failed, ${warn} warning(s), ${pass} passed`)
874
- lines.push(fail === 0
875
- ? 'no blocking problem found: this copy matches what it claims to be'
876
- : 'blocking checks failed; run the fix lines above, then re-run doctor')
877
- return lines.join('\n')
878
- }
1
+ /**
2
+ * Read-only installation checks for dsh-superagent.
3
+ *
4
+ * Two real releases failed in the same shape: the package installed cleanly and
5
+ * then did nothing. One shipped an `index.js` that imported `lib/memory.js`,
6
+ * `lib/notify.js`, and `lib/lock.js` while `package.json` `files` left them out,
7
+ * so `npm pack` produced 15 files and the first `import` threw. Another profile
8
+ * was left half-unpacked by an interrupted install: `package.json` said 0.9.1
9
+ * while only five of eleven `lib` files existed, so the host could not mount
10
+ * the plugin and nothing said why.
11
+ *
12
+ * `doctor` compares the three layers that have to agree — what the code
13
+ * imports, what `files` promises, and what is actually on disk — plus the
14
+ * profile wiring and the registered tool count. It only reads: no install, no
15
+ * mount, no edit to the profile. The one write-free exception is the optional
16
+ * registry comparison, which downloads one public tarball to hash it.
17
+ *
18
+ * @module dsh-superagent/doctor
19
+ */
20
+ import { exec, execFile } from 'node:child_process'
21
+ import { createHash } from 'node:crypto'
22
+ import fsp from 'node:fs/promises'
23
+ import os from 'node:os'
24
+ import path from 'node:path'
25
+ import { gunzipSync } from 'node:zlib'
26
+
27
+ export const PACKAGE_NAME = '@xiangyixie/dsh-superagent'
28
+
29
+ /** Tools this package version must register for the plugin to be complete. */
30
+ export const TOOL_NAMES = [
31
+ 'superagent_start',
32
+ 'superagent_status',
33
+ 'superagent_list',
34
+ 'superagent_cancel',
35
+ 'superagent_resume',
36
+ 'superagent_followup',
37
+ 'superagent_inject',
38
+ 'superagent_answer',
39
+ 'superagent_memory',
40
+ 'superagent_template',
41
+ 'superagent_schedule',
42
+ 'superagent_audit',
43
+ ]
44
+
45
+ /** Files npm always includes, whether or not `files` lists them. */
46
+ const ALWAYS_PACKED = new Set(['package.json'])
47
+
48
+ /**
49
+ * Relative import specifiers: `import x from './y.js'`, `export … from './y.js'`,
50
+ * and `import './y.js'`. Only specifiers that start with `.` are package files;
51
+ * bare names are built-ins or dependencies and are not ours to ship.
52
+ */
53
+ const RELATIVE_IMPORT = /\b(?:from\s*|import\s*\(\s*|import\s*)['"](\.[^'"]+)['"]/g
54
+
55
+ export function normalizeRel(value) {
56
+ return String(value).replace(/\\/g, '/').replace(/^\.\//, '')
57
+ }
58
+
59
+ /**
60
+ * Remove comments while keeping string literals intact. A doc comment that
61
+ * mentions an import path must not become a dependency of the package.
62
+ */
63
+ export function stripComments(source) {
64
+ const text = String(source)
65
+ let out = ''
66
+ let state = null
67
+ for (let index = 0; index < text.length; index++) {
68
+ const char = text[index]
69
+ const next = text[index + 1]
70
+ if (state === null) {
71
+ if (char === '/' && next === '/') {
72
+ state = 'line'
73
+ index += 1
74
+ } else if (char === '/' && next === '*') {
75
+ state = 'block'
76
+ index += 1
77
+ } else {
78
+ if (char === "'" || char === '"' || char === '`') state = char
79
+ out += char
80
+ }
81
+ } else if (state === 'line') {
82
+ if (char === '\n') {
83
+ state = null
84
+ out += char
85
+ }
86
+ } else if (state === 'block') {
87
+ if (char === '*' && next === '/') {
88
+ state = null
89
+ index += 1
90
+ } else if (char === '\n') {
91
+ out += char
92
+ }
93
+ } else {
94
+ out += char
95
+ if (char === '\\') {
96
+ if (index + 1 < text.length) out += text[++index]
97
+ } else if (char === state) {
98
+ state = null
99
+ }
100
+ }
101
+ }
102
+ return out
103
+ }
104
+
105
+ /** Every relative specifier a source file mentions, in order, without duplicates. */
106
+ export function scanRelativeImports(source) {
107
+ const found = new Set()
108
+ for (const match of stripComments(source).matchAll(RELATIVE_IMPORT)) {
109
+ if (match[1].startsWith('..') || match[1].startsWith('./')) found.add(match[1])
110
+ }
111
+ return [...found]
112
+ }
113
+
114
+ /**
115
+ * Tool names a plugin entry point registers.
116
+ *
117
+ * The registration call is split at `ctx.tools.register(` and the first `name:`
118
+ * in each chunk is the tool. That survives reformatting far better than one
119
+ * giant regular expression, and it still counts a registration whose body the
120
+ * parser would reject.
121
+ */
122
+ export function readRegisteredTools(source) {
123
+ const names = []
124
+ for (const chunk of String(source).split('ctx.tools.register(').slice(1)) {
125
+ const match = /name:\s*['"]([^'"]+)['"]/.exec(chunk)
126
+ if (match) names.push(match[1])
127
+ }
128
+ return names
129
+ }
130
+
131
+ function parseVersion(value) {
132
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(value ?? '').trim())
133
+ return match ? { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]) } : null
134
+ }
135
+
136
+ function compareVersions(left, right) {
137
+ for (const key of ['major', 'minor', 'patch']) {
138
+ if (left[key] !== right[key]) return left[key] < right[key] ? -1 : 1
139
+ }
140
+ return 0
141
+ }
142
+
143
+ function satisfiesToken(token, version) {
144
+ const match = /^(>=|<=|>|<|=|\^|~)?\s*(\d+)(?:\.(\d+))?(?:\.(\d+))?$/.exec(token)
145
+ if (!match) return false
146
+ const target = {
147
+ major: Number(match[2]),
148
+ minor: Number(match[3] ?? 0),
149
+ patch: Number(match[4] ?? 0),
150
+ }
151
+ const relation = compareVersions(version, target)
152
+ switch (match[1] ?? '=') {
153
+ case '>=': return relation >= 0
154
+ case '>': return relation > 0
155
+ case '<=': return relation <= 0
156
+ case '<': return relation < 0
157
+ case '=': return relation === 0
158
+ case '^': {
159
+ if (relation < 0) return false
160
+ const ceiling = target.major > 0
161
+ ? { major: target.major + 1, minor: 0, patch: 0 }
162
+ : { major: 0, minor: target.minor + 1, patch: 0 }
163
+ return compareVersions(version, ceiling) < 0
164
+ }
165
+ case '~': {
166
+ if (relation < 0) return false
167
+ return compareVersions(version, { major: target.major, minor: target.minor + 1, patch: 0 }) < 0
168
+ }
169
+ default: return false
170
+ }
171
+ }
172
+
173
+ /**
174
+ * Test a plain semver range against a version. Supports `||`, space-separated
175
+ * conjunctions, and the comparators an `engines` field actually uses. Anything
176
+ * it cannot parse fails closed, because "unknown range" must not read as "fine".
177
+ */
178
+ export function satisfiesRange(range, version) {
179
+ const parsed = parseVersion(version)
180
+ if (!parsed) return false
181
+ const text = String(range ?? '').trim()
182
+ if (!text || text === '*') return true
183
+ return text.split('||').some(part => {
184
+ const tokens = part.trim().split(/\s+/).filter(Boolean)
185
+ return tokens.length === 0 || tokens.every(token => satisfiesToken(token, parsed))
186
+ })
187
+ }
188
+
189
+ async function exists(target) {
190
+ try {
191
+ await fsp.access(target)
192
+ return true
193
+ } catch {
194
+ return false
195
+ }
196
+ }
197
+
198
+ export async function readPackageJson(packageRoot) {
199
+ const file = path.join(packageRoot, 'package.json')
200
+ let text
201
+ try {
202
+ text = await fsp.readFile(file, 'utf8')
203
+ } catch (error) {
204
+ throw new Error(`cannot read ${file}: ${error?.message ?? error}`)
205
+ }
206
+ try {
207
+ return JSON.parse(text)
208
+ } catch (error) {
209
+ throw new Error(`${file} is not valid JSON: ${error?.message ?? error}`)
210
+ }
211
+ }
212
+
213
+ function exportTargets(exportsField) {
214
+ const targets = []
215
+ const walk = value => {
216
+ if (typeof value === 'string') targets.push(value)
217
+ else if (Array.isArray(value)) value.forEach(walk)
218
+ else if (value && typeof value === 'object') Object.values(value).forEach(walk)
219
+ }
220
+ walk(exportsField)
221
+ return targets
222
+ }
223
+
224
+ /** Resolve `./x.js` written in `fromRel` to a repo-relative path that exists. */
225
+ async function resolveLocalFile(packageRoot, fromRel, specifier) {
226
+ const joined = path.posix.normalize(path.posix.join(path.posix.dirname(fromRel), specifier))
227
+ if (joined.startsWith('..')) return null
228
+ const candidates = [joined]
229
+ if (!path.posix.extname(joined)) candidates.push(`${joined}.js`, `${joined}/index.js`)
230
+ for (const candidate of candidates) {
231
+ if (await exists(path.join(packageRoot, candidate))) return candidate
232
+ }
233
+ return joined
234
+ }
235
+
236
+ /**
237
+ * Files the package cannot run without: entry points plus everything they
238
+ * import, transitively. `package.json` is included because `index.js` reads its
239
+ * version, but npm always packs it, so it needs no `files` entry.
240
+ */
241
+ export async function requiredFiles(packageRoot) {
242
+ const pkg = await readPackageJson(packageRoot)
243
+ const roots = new Set()
244
+ const addRoot = value => {
245
+ if (typeof value === 'string' && value.trim()) roots.add(normalizeRel(value.trim()))
246
+ }
247
+ addRoot(pkg.main)
248
+ for (const value of Object.values(pkg.bin ?? {})) addRoot(value)
249
+ exportTargets(pkg.exports).forEach(addRoot)
250
+ addRoot(pkg.dsh?.bundle?.patch)
251
+ if (roots.size === 0) addRoot('lib/index.js')
252
+
253
+ const required = new Set()
254
+ const queue = [...roots]
255
+ while (queue.length > 0) {
256
+ const rel = queue.shift()
257
+ if (required.has(rel)) continue
258
+ required.add(rel)
259
+ if (!rel.endsWith('.js')) continue
260
+ let source
261
+ try {
262
+ source = await fsp.readFile(path.join(packageRoot, rel), 'utf8')
263
+ } catch {
264
+ continue
265
+ }
266
+ for (const specifier of scanRelativeImports(source)) {
267
+ const resolved = await resolveLocalFile(packageRoot, rel, specifier)
268
+ if (resolved && !required.has(resolved)) queue.push(resolved)
269
+ }
270
+ }
271
+ return [...required].sort()
272
+ }
273
+
274
+ function matchesFilesEntry(rel, entry) {
275
+ const pattern = normalizeRel(entry).replace(/\/+$/, '')
276
+ if (!pattern) return false
277
+ if (!pattern.includes('*')) return rel === pattern || rel.startsWith(`${pattern}/`)
278
+ const escaped = pattern
279
+ .split('*')
280
+ .map(part => part.replace(/[.+^${}()|[\]\\]/g, '\\$&'))
281
+ .join('[^/]*')
282
+ return new RegExp(`^${escaped}$`).test(rel) || new RegExp(`^${escaped}/`).test(rel)
283
+ }
284
+
285
+ /**
286
+ * Compare one package directory's imports, `files` whitelist, and disk contents.
287
+ * @param {string} packageRoot - absolute package directory.
288
+ */
289
+ export async function auditLayout(packageRoot) {
290
+ const pkg = await readPackageJson(packageRoot)
291
+ const required = await requiredFiles(packageRoot)
292
+ const declared = Array.isArray(pkg.files) ? pkg.files.map(normalizeRel) : []
293
+
294
+ const missingFromDisk = []
295
+ for (const rel of required) {
296
+ if (!(await exists(path.join(packageRoot, rel)))) missingFromDisk.push(rel)
297
+ }
298
+ const uncovered = required.filter(rel => !ALWAYS_PACKED.has(rel)
299
+ && !declared.some(entry => matchesFilesEntry(rel, entry)))
300
+
301
+ const missingDeclared = []
302
+ for (const entry of declared) {
303
+ if (entry.includes('*')) continue
304
+ if (!(await exists(path.join(packageRoot, entry)))) missingDeclared.push(entry)
305
+ }
306
+
307
+ let libOnDisk = 0
308
+ try {
309
+ const entries = await fsp.readdir(path.join(packageRoot, 'lib'), { withFileTypes: true })
310
+ libOnDisk = entries.filter(entry => entry.isFile() && entry.name.endsWith('.js')).length
311
+ } catch {
312
+ libOnDisk = 0
313
+ }
314
+ const libDeclared = declared.filter(entry => /^lib\/[^/*]+\.js$/.test(entry)).length
315
+
316
+ return {
317
+ packageRoot,
318
+ name: pkg.name ?? null,
319
+ version: pkg.version ?? null,
320
+ engines: pkg.engines ?? {},
321
+ declared,
322
+ required,
323
+ missingFromDisk,
324
+ uncovered,
325
+ missingDeclared,
326
+ libOnDisk,
327
+ libDeclared,
328
+ }
329
+ }
330
+
331
+ /** Paths of everything `npm pack` would include, via a dry run (no tarball). */
332
+ export function packFileList(packageRoot) {
333
+ const args = 'pack --dry-run --json --ignore-scripts'
334
+ const options = { cwd: packageRoot, timeout: 120_000, maxBuffer: 16 * 1024 * 1024 }
335
+ return new Promise((resolve, reject) => {
336
+ const done = (error, stdout, stderr) => {
337
+ if (error) {
338
+ reject(new Error(`npm pack --dry-run failed: ${(stderr || error.message || '').trim()}`))
339
+ return
340
+ }
341
+ try {
342
+ const start = stdout.indexOf('[')
343
+ const parsed = JSON.parse(start >= 0 ? stdout.slice(start) : stdout)
344
+ resolve((parsed[0]?.files ?? []).map(file => normalizeRel(file.path)))
345
+ } catch (parseError) {
346
+ reject(new Error(`cannot parse npm pack JSON: ${parseError.message}`))
347
+ }
348
+ }
349
+ // npm is a .cmd shim on Windows, which needs a shell; the command string is
350
+ // composed only of literals, so there is nothing to escape.
351
+ if (process.platform === 'win32') exec(`npm ${args}`, options, done)
352
+ else execFile('npm', args.split(' '), options, done)
353
+ })
354
+ }
355
+
356
+ /**
357
+ * The CI guard: every file the code imports must appear in the tarball, and
358
+ * every plain `files` entry must actually be packed. A `files` entry npm cannot
359
+ * find is silently skipped, which is how an import ships a promise instead of a
360
+ * module.
361
+ * @param {{ packageRoot: string, packed: string[] }} input - dry-run file list.
362
+ */
363
+ export async function auditPackedFiles({ packageRoot, packed }) {
364
+ const layout = await auditLayout(packageRoot)
365
+ const shipped = new Set(packed.map(normalizeRel))
366
+ const missing = layout.required.filter(rel => !ALWAYS_PACKED.has(rel) && !shipped.has(rel))
367
+ const notPacked = layout.declared.filter(entry => !entry.includes('*')
368
+ && !ALWAYS_PACKED.has(entry)
369
+ && !shipped.has(entry))
370
+ return { ...layout, packed: [...shipped], missing, notPacked }
371
+ }
372
+
373
+ function readTarString(header, start, length) {
374
+ return header.toString('utf8', start, start + length).replace(/\0.*$/s, '').trimEnd()
375
+ }
376
+
377
+ /**
378
+ * Minimal ustar reader: only what a published npm tarball contains. Returns
379
+ * regular files with their bytes, so hashes can be compared without unpacking
380
+ * to disk.
381
+ */
382
+ export function readTarEntries(buffer) {
383
+ const data = buffer[0] === 0x1f && buffer[1] === 0x8b ? gunzipSync(buffer) : buffer
384
+ const entries = []
385
+ let offset = 0
386
+ while (offset + 512 <= data.length) {
387
+ const header = data.subarray(offset, offset + 512)
388
+ if (header.every(byte => byte === 0)) break
389
+ const name = readTarString(header, 0, 100)
390
+ const prefix = readTarString(header, 345, 155)
391
+ const size = Number.parseInt(readTarString(header, 124, 12), 8) || 0
392
+ const type = String.fromCharCode(header[156] || 48)
393
+ offset += 512
394
+ const fullName = normalizeRel(prefix ? `${prefix}/${name}` : name)
395
+ if (type === '0' || type === '\0' || type === '7') {
396
+ entries.push({ name: fullName.replace(/^package\//, ''), data: data.subarray(offset, offset + size) })
397
+ }
398
+ offset += Math.ceil(size / 512) * 512
399
+ }
400
+ return entries
401
+ }
402
+
403
+ function sha256(data) {
404
+ return createHash('sha256').update(data).digest('hex')
405
+ }
406
+
407
+ /**
408
+ * Compare the files of the installed copy with the published tarball for the
409
+ * same version. Networks are optional: an unreachable registry degrades this
410
+ * check to a warning with the command that would confirm it by hand.
411
+ * @param {object} input - package directory, fetch implementation, timeout.
412
+ */
413
+ export async function auditRegistry({ packageRoot, fetchImpl = globalThis.fetch, timeoutMs = 8000, profileName = null } = {}) {
414
+ const pkg = await readPackageJson(packageRoot)
415
+ const name = pkg.name ?? PACKAGE_NAME
416
+ const version = pkg.version ?? '0.0.0'
417
+ const registry = String(pkg.publishConfig?.registry ?? 'https://registry.npmjs.org').replace(/\/+$/, '')
418
+ const metadataUrl = `${registry}/${name.replace('/', '%2F')}/${version}`
419
+ const offlineFix = `npm view ${name}@${version} dist.tarball`
420
+
421
+ if (typeof fetchImpl !== 'function') {
422
+ return { status: 'warn', detail: ['no fetch implementation; registry comparison skipped'], fix: offlineFix }
423
+ }
424
+ try {
425
+ const metaResponse = await fetchImpl(metadataUrl, {
426
+ headers: { accept: 'application/json' },
427
+ signal: AbortSignal.timeout(timeoutMs),
428
+ })
429
+ if (!metaResponse.ok) throw new Error(`registry returned HTTP ${metaResponse.status}`)
430
+ const meta = await metaResponse.json()
431
+ const tarballUrl = meta?.dist?.tarball
432
+ if (!tarballUrl) throw new Error('registry metadata has no dist.tarball')
433
+
434
+ const tarResponse = await fetchImpl(tarballUrl, { signal: AbortSignal.timeout(timeoutMs) })
435
+ if (!tarResponse.ok) throw new Error(`tarball returned HTTP ${tarResponse.status}`)
436
+ const tarball = Buffer.from(await tarResponse.arrayBuffer())
437
+ const published = new Map(readTarEntries(tarball).map(entry => [entry.name, sha256(entry.data)]))
438
+
439
+ const missing = []
440
+ const different = []
441
+ let compared = 0
442
+ for (const [file, digest] of published) {
443
+ // package.json is rewritten by tooling on some installs; the version field
444
+ // is checked by the layout audit instead of by byte equality.
445
+ if (file === 'package.json') continue
446
+ let local
447
+ try {
448
+ local = await fsp.readFile(path.join(packageRoot, file))
449
+ } catch {
450
+ missing.push(file)
451
+ continue
452
+ }
453
+ compared += 1
454
+ if (sha256(local) !== digest) different.push(file)
455
+ }
456
+
457
+ const extra = []
458
+ for (const file of await listFilesRecursive(packageRoot)) {
459
+ if (file === 'package.json') continue
460
+ if (!published.has(file)) extra.push(file)
461
+ }
462
+
463
+ if (missing.length > 0 || different.length > 0) {
464
+ const detail = []
465
+ if (missing.length > 0) {
466
+ detail.push(`${missing.length} published file(s) are missing from the installed copy:`)
467
+ detail.push(...missing.slice(0, 8).map(file => ` ${file}`))
468
+ }
469
+ if (different.length > 0) {
470
+ detail.push(`${different.length} file(s) differ from ${name}@${version}:`)
471
+ detail.push(...different.slice(0, 8).map(file => ` ${file}`))
472
+ }
473
+ return {
474
+ status: 'fail',
475
+ detail,
476
+ fix: 'this copy is not the published artifact; reinstall it from the registry:\n'
477
+ + reinstallCommand(profileName, version)
478
+ + '\n# if it came from a local tarball, rebuild that tarball and reinstall it instead',
479
+ }
480
+ }
481
+ const detail = [`${compared} file(s) match ${name}@${version} by sha256`]
482
+ if (extra.length > 0) detail.push(`${extra.length} local file(s) are not in the published tarball: ${extra.slice(0, 5).join(', ')}`)
483
+ return { status: extra.length > 0 ? 'warn' : 'pass', detail }
484
+ } catch (error) {
485
+ return {
486
+ status: 'warn',
487
+ detail: [`registry comparison skipped: ${error?.message ?? error}`, 'offline is fine; the other checks still ran'],
488
+ fix: offlineFix,
489
+ }
490
+ }
491
+ }
492
+
493
+ async function listFilesRecursive(root) {
494
+ const found = []
495
+ const walk = async dir => {
496
+ let entries
497
+ try {
498
+ entries = await fsp.readdir(dir, { withFileTypes: true })
499
+ } catch {
500
+ return
501
+ }
502
+ for (const entry of entries) {
503
+ const abs = path.join(dir, entry.name)
504
+ if (entry.isDirectory()) await walk(abs)
505
+ else if (entry.isFile()) found.push(normalizeRel(path.relative(root, abs)))
506
+ }
507
+ }
508
+ await walk(root)
509
+ return found.sort()
510
+ }
511
+
512
+ /** Resolve `--profile web` to `<DSH_HOME>/profiles/web`; a path is used as-is. */
513
+ export function resolveProfileDir(profile, dshHome) {
514
+ if (!profile) return null
515
+ if (profile === '.' || profile === '..' || profile.includes('/') || profile.includes('\\')) {
516
+ return path.resolve(profile)
517
+ }
518
+ return path.join(dshHome, 'profiles', profile)
519
+ }
520
+
521
+ /**
522
+ * Infer the profile from a package path such as
523
+ * `<DSH_HOME>/profiles/web/node_modules/@xiangyixie/dsh-superagent`.
524
+ */
525
+ export function inferProfileDir(packageRoot) {
526
+ const parts = path.resolve(packageRoot).split(path.sep)
527
+ const index = parts.lastIndexOf('profiles')
528
+ if (index < 0 || index + 1 >= parts.length) return null
529
+ const name = parts[index + 1]
530
+ if (!name || name === 'node_modules') return null
531
+ return parts.slice(0, index + 2).join(path.sep)
532
+ }
533
+
534
+ function reinstallCommand(profileName, version) {
535
+ return `dsh plugin --profile ${profileName ?? '<profile>'} add ${PACKAGE_NAME}@${version ?? '<version>'}`
536
+ }
537
+
538
+ function cleanCopyCommand(packageDir) {
539
+ return process.platform === 'win32'
540
+ ? `Remove-Item -Recurse -Force "${packageDir}"`
541
+ : `rm -rf "${packageDir}"`
542
+ }
543
+
544
+ function check(id, title, status, detail = [], fix = null) {
545
+ return { id, title, status, detail, fix }
546
+ }
547
+
548
+ function checkNodeEngine(layout, nodeVersion) {
549
+ const range = layout.engines?.node
550
+ if (!range) {
551
+ return check('node-engine', 'Node version', 'warn', ['package.json declares no engines.node, so no minimum is enforced'])
552
+ }
553
+ if (satisfiesRange(range, nodeVersion)) {
554
+ return check('node-engine', 'Node version', 'pass', [`v${nodeVersion} satisfies "${range}"`])
555
+ }
556
+ return check('node-engine', 'Node version', 'fail', [
557
+ `installed Node is v${nodeVersion}, but package.json requires "${range}"`,
558
+ 'the host and this package are running on an unsupported Node; imports can fail at startup',
559
+ ], `install Node ${range} (or newer) and run the host on it:\nnode --version`)
560
+ }
561
+
562
+ function checkFilesCoverage(layout, { profileName }) {
563
+ const detail = []
564
+ if (layout.uncovered.length > 0) {
565
+ detail.push(`${layout.uncovered.length} imported file(s) are not matched by package.json "files":`)
566
+ detail.push(...layout.uncovered.slice(0, 8).map(file => ` ${file}`))
567
+ if (layout.uncovered.length > 8) detail.push(` ... and ${layout.uncovered.length - 8} more`)
568
+ }
569
+ if (layout.missingFromDisk.length > 0) {
570
+ detail.push(`${layout.missingFromDisk.length} imported file(s) do not exist on disk:`)
571
+ detail.push(...layout.missingFromDisk.slice(0, 8).map(file => ` ${file}`))
572
+ }
573
+ if (detail.length === 0) {
574
+ return check('package-files', 'Package files', 'pass', [
575
+ `${layout.required.length} file(s) reachable from the entry points; all are shipped by "files"`,
576
+ ])
577
+ }
578
+ const fixLines = []
579
+ if (layout.uncovered.length > 0) {
580
+ fixLines.push('add the missing entry to "files" in package.json, then pack and reinstall:')
581
+ fixLines.push(...layout.uncovered.slice(0, 8).map(file => ` "${file}"`))
582
+ fixLines.push('npm pack --dry-run --json')
583
+ }
584
+ if (layout.missingFromDisk.length > 0) {
585
+ fixLines.push('restore the file from git, or reinstall a complete copy:')
586
+ fixLines.push(reinstallCommand(profileName, layout.version))
587
+ }
588
+ return check('package-files', 'Package files', 'fail', detail, fixLines.join('\n'))
589
+ }
590
+
591
+ function checkInstalledCopy(layout, { profileName }) {
592
+ if (layout.missingDeclared.length === 0 && layout.libDeclared <= layout.libOnDisk) {
593
+ return check('installed-copy', 'Installed copy', 'pass', [
594
+ `package.json ${layout.version ?? '(no version)'} declares ${layout.declared.length} packed file(s); `
595
+ + `${layout.libOnDisk} lib file(s) on disk`,
596
+ ])
597
+ }
598
+ const detail = [
599
+ `package.json says version ${layout.version ?? '(none)'} and "files" lists ${layout.libDeclared} lib file(s), `
600
+ + `but only ${layout.libOnDisk} are on disk`,
601
+ ]
602
+ if (layout.missingDeclared.length > 0) {
603
+ detail.push(`${layout.missingDeclared.length} declared file(s) are absent:`)
604
+ detail.push(...layout.missingDeclared.slice(0, 8).map(file => ` ${file}`))
605
+ if (layout.missingDeclared.length > 8) detail.push(` ... and ${layout.missingDeclared.length - 8} more`)
606
+ }
607
+ detail.push('this is what an interrupted install leaves behind: package.json is complete, the unpacked tree is not')
608
+ return check('installed-copy', 'Installed copy', 'fail', detail, [
609
+ 'remove the partial copy and install it again:',
610
+ cleanCopyCommand(layout.packageRoot),
611
+ reinstallCommand(profileName, layout.version),
612
+ ].join('\n'))
613
+ }
614
+
615
+ function checkSyntax(packageRoot, required, { profileName, version }) {
616
+ return new Promise(resolve => {
617
+ const files = required.filter(file => file.endsWith('.js'))
618
+ const broken = []
619
+ const verify = index => {
620
+ if (index >= files.length) {
621
+ if (broken.length === 0) {
622
+ resolve(check('syntax', 'File syntax', 'pass', [`${files.length} shipped JavaScript file(s) parse`]))
623
+ return
624
+ }
625
+ resolve(check('syntax', 'File syntax', 'fail', [
626
+ `${broken.length} shipped file(s) cannot be parsed (truncated by a partial unpack or a broken build):`,
627
+ ...broken.map(item => ` ${item.file}: ${item.reason}`),
628
+ ], `reinstall a complete copy:\n${reinstallCommand(profileName, version)}`))
629
+ return
630
+ }
631
+ const file = files[index]
632
+ execFile(process.execPath, ['--check', path.join(packageRoot, file)], { timeout: 20_000 }, (error, _stdout, stderr) => {
633
+ if (error) {
634
+ const reason = String(stderr || error.message).split('\n').find(line => line.trim()) ?? 'parse error'
635
+ broken.push({ file, reason: reason.replace(/^.*?Error:\s*/, '').trim() })
636
+ }
637
+ verify(index + 1)
638
+ })
639
+ }
640
+ verify(0)
641
+ })
642
+ }
643
+
644
+ async function checkTools(packageDir, expected, { profileName, version }) {
645
+ const entry = path.join(packageDir, 'lib', 'index.js')
646
+ let source
647
+ try {
648
+ source = await fsp.readFile(entry, 'utf8')
649
+ } catch {
650
+ return check('tools', 'Registered tools', 'fail', [
651
+ `cannot read ${entry}`,
652
+ 'without the entry point the host mounts no tools at all',
653
+ ], `reinstall a complete copy:\n${reinstallCommand(profileName, version)}`)
654
+ }
655
+ const names = readRegisteredTools(source)
656
+ const missing = expected.filter(name => !names.includes(name))
657
+ const extra = names.filter(name => !expected.includes(name))
658
+ if (missing.length === 0 && extra.length === 0) {
659
+ return check('tools', 'Registered tools', 'pass', [`${names.length}/${expected.length} expected tools are registered`])
660
+ }
661
+ const detail = [`registered ${names.length} of ${expected.length} expected tools`]
662
+ if (missing.length > 0) detail.push(`missing: ${missing.join(', ')}`)
663
+ if (extra.length > 0) detail.push(`unexpected: ${extra.join(', ')}`)
664
+ return check('tools', 'Registered tools', 'fail', detail, [
665
+ 'this copy registers a different tool set than the version claims; reinstall it:',
666
+ reinstallCommand(profileName, version),
667
+ ].join('\n'))
668
+ }
669
+
670
+ async function checkPatchFile(packageDir, pkg, { profileName }) {
671
+ const patchRel = pkg?.dsh?.bundle?.patch
672
+ if (typeof patchRel !== 'string' || !patchRel.trim()) {
673
+ return check('patch', 'Bundle patch', 'fail', [
674
+ 'package.json has no dsh.bundle.patch, so the host has no row to mount',
675
+ ], `reinstall a complete copy:\n${reinstallCommand(profileName, pkg?.version)}`)
676
+ }
677
+ const file = path.join(packageDir, normalizeRel(patchRel))
678
+ let text
679
+ try {
680
+ text = await fsp.readFile(file, 'utf8')
681
+ } catch {
682
+ return check('patch', 'Bundle patch', 'fail', [
683
+ `package.json points at ${patchRel}, but that file is not in the package`,
684
+ ], `reinstall a complete copy:\n${reinstallCommand(profileName, pkg?.version)}`)
685
+ }
686
+ const namesPackage = text.includes(pkg?.name ?? PACKAGE_NAME)
687
+ const inserts = /(^|\n)\s*-\s*insert:/.test(text)
688
+ if (!inserts || !namesPackage) {
689
+ return check('patch', 'Bundle patch', 'fail', [
690
+ `${patchRel} does not insert a row for ${pkg?.name ?? PACKAGE_NAME}`,
691
+ 'without the row the plugin is installed but never mounted',
692
+ ], `reinstall a complete copy:\n${reinstallCommand(profileName, pkg?.version)}`)
693
+ }
694
+ return check('patch', 'Bundle patch', 'pass', [`${patchRel} inserts the plugin row at profile scope`])
695
+ }
696
+
697
+ async function checkProfile(profileDir, profileName) {
698
+ if (!(await exists(profileDir))) {
699
+ return check('profile', 'DSH profile', 'fail', [
700
+ `no profile at ${profileDir}`,
701
+ 'nothing is installed there, so no superagent tool can exist in it',
702
+ ], `${reinstallCommand(profileName, null)}\n# if DSH_HOME points elsewhere, pass the full path: --profile "<path>"`)
703
+ }
704
+ const detail = []
705
+ try {
706
+ await readPackageJson(profileDir)
707
+ } catch (error) {
708
+ return check('profile', 'DSH profile', 'fail', [String(error.message)], [
709
+ 'make the profile readable, then reinstall the plugin:',
710
+ reinstallCommand(profileName, null),
711
+ ].join('\n'))
712
+ }
713
+ const hasNodeModules = await exists(path.join(profileDir, 'node_modules'))
714
+ const hasRoot = await exists(path.join(profileDir, 'cordis.yml'))
715
+ if (!hasNodeModules) {
716
+ detail.push('node_modules is missing, so no plugin copy is installed')
717
+ }
718
+ if (!hasRoot) {
719
+ detail.push('cordis.yml is missing; the host composes an empty root, which usually still works')
720
+ }
721
+ if (!hasNodeModules) {
722
+ return check('profile', 'DSH profile', 'fail', detail, [
723
+ 'install the plugin into this profile:',
724
+ reinstallCommand(profileName, null),
725
+ ].join('\n'))
726
+ }
727
+ return check('profile', 'DSH profile', hasRoot ? 'pass' : 'warn', detail.length > 0
728
+ ? detail
729
+ : [`${profileDir} has package.json, cordis.yml, and node_modules`])
730
+ }
731
+
732
+ async function checkBundle(profileDir, packageName, profileName, version) {
733
+ try {
734
+ const pkg = await readPackageJson(profileDir)
735
+ const bundles = pkg?.dsh?.profile?.bundles
736
+ if (Array.isArray(bundles) && bundles.includes(packageName)) {
737
+ return check('bundle', 'Profile registration', 'pass', [
738
+ `dsh.profile.bundles includes ${packageName}`,
739
+ ])
740
+ }
741
+ return check('bundle', 'Profile registration', 'fail', [
742
+ `${packageName} is not in dsh.profile.bundles, so its cordis.patch.yml is never loaded`,
743
+ 'the installed files are fine; the profile simply does not mount them',
744
+ ], `${reinstallCommand(profileName, version)}\n# then confirm the row appears:\ndsh --profile ${profileName ?? '<profile>'} --dump-config`)
745
+ } catch (error) {
746
+ return check('bundle', 'Profile registration', 'fail', [String(error.message)])
747
+ }
748
+ }
749
+
750
+ async function checkVersionDrift(packageRoot, targetDir, profileName) {
751
+ if (path.resolve(packageRoot) === path.resolve(targetDir)) return null
752
+ try {
753
+ const checkout = await readPackageJson(packageRoot)
754
+ const installed = await readPackageJson(targetDir)
755
+ if (checkout.version === installed.version) return null
756
+ return check('version', 'Version match', 'warn', [
757
+ `installed copy is ${installed.version}, this checkout is ${checkout.version}`,
758
+ `${targetDir} did not come from this source tree; reinstall it before trusting a fix here`,
759
+ ], reinstallCommand(profileName, checkout.version))
760
+ } catch {
761
+ return null
762
+ }
763
+ }
764
+
765
+ /**
766
+ * Run every check and return structured results. Rendering is separate so the
767
+ * CLI and the tests see the same verdicts.
768
+ * @param {object} [options] - paths, offline switch, and injectable fetch.
769
+ */
770
+ export async function runDoctor(options = {}) {
771
+ const packageRoot = path.resolve(options.packageRoot ?? process.cwd())
772
+ const dshHome = options.dshHome ?? process.env.DSH_HOME?.trim() ?? path.join(os.homedir(), '.dsh')
773
+ const profileDir = options.profile === undefined
774
+ ? inferProfileDir(packageRoot)
775
+ : resolveProfileDir(options.profile, dshHome)
776
+ const profileName = profileDir ? path.basename(profileDir) : null
777
+ const nodeVersion = options.nodeVersion ?? process.versions.node
778
+
779
+ let pkg
780
+ try {
781
+ pkg = await readPackageJson(packageRoot)
782
+ } catch (error) {
783
+ return {
784
+ packageRoot,
785
+ profileDir,
786
+ profileName,
787
+ targetDir: packageRoot,
788
+ version: null,
789
+ nodeVersion,
790
+ ok: false,
791
+ checks: [check('package', 'Package', 'fail', [String(error.message)], 'run this command from an installed copy or pass --package <dir>')],
792
+ }
793
+ }
794
+ const packageName = pkg.name ?? PACKAGE_NAME
795
+ const candidate = profileDir
796
+ ? path.join(profileDir, 'node_modules', ...packageName.split('/'))
797
+ : null
798
+ const installedDir = candidate && await exists(candidate) ? candidate : null
799
+ const targetDir = installedDir ?? packageRoot
800
+ const targetPkg = installedDir ? await readPackageJson(installedDir).catch(() => pkg) : pkg
801
+
802
+ const layout = await auditLayout(targetDir)
803
+ const checks = []
804
+ checks.push(checkNodeEngine(layout, nodeVersion))
805
+ checks.push(checkFilesCoverage(layout, { profileName }))
806
+ checks.push(checkInstalledCopy(layout, { profileName }))
807
+ checks.push(await checkSyntax(targetDir, layout.required, { profileName, version: targetPkg.version }))
808
+ if (options.online === false) {
809
+ checks.push(check('registry', 'Registry match', 'warn', ['registry comparison skipped (--offline)'], `npm view ${packageName}@${targetPkg.version} dist.tarball`))
810
+ } else {
811
+ const registry = await auditRegistry({
812
+ packageRoot: targetDir,
813
+ fetchImpl: options.fetchImpl,
814
+ timeoutMs: options.registryTimeoutMs,
815
+ profileName,
816
+ })
817
+ checks.push(check('registry', 'Registry match', registry.status, registry.detail, registry.fix ?? null))
818
+ }
819
+ checks.push(await checkTools(targetDir, options.expectedTools ?? TOOL_NAMES, { profileName, version: targetPkg.version }))
820
+ checks.push(await checkPatchFile(targetDir, targetPkg, { profileName }))
821
+ if (profileDir) {
822
+ checks.push(await checkProfile(profileDir, profileName))
823
+ checks.push(await checkBundle(profileDir, packageName, profileName, targetPkg.version))
824
+ const drift = await checkVersionDrift(packageRoot, targetDir, profileName)
825
+ if (drift) checks.push(drift)
826
+ } else {
827
+ checks.push(check('profile', 'DSH profile', 'warn', [
828
+ 'no profile given, so profile wiring was not checked',
829
+ 'run again with --profile <name> (for example: --profile web)',
830
+ ]))
831
+ }
832
+ const counts = { pass: 0, warn: 0, fail: 0 }
833
+ for (const item of checks) counts[item.status] += 1
834
+ return {
835
+ packageRoot,
836
+ profileDir,
837
+ profileName,
838
+ targetDir,
839
+ version: targetPkg.version ?? null,
840
+ nodeVersion,
841
+ checks,
842
+ counts,
843
+ ok: counts.fail === 0,
844
+ }
845
+ }
846
+
847
+ const STATUS_COLOR = { pass: '32', warn: '33', fail: '31' }
848
+ const STATUS_LABEL = { pass: 'PASS', warn: 'WARN', fail: 'FAIL' }
849
+
850
+ /**
851
+ * Human report: one block per check, then the exact commands that fix what is
852
+ * broken. Commands sit on their own lines so they can be copied verbatim.
853
+ */
854
+ export function renderReport(result, { color = false } = {}) {
855
+ const paint = (code, text) => (color ? `\x1b[${code}m${text}\x1b[0m` : text)
856
+ const lines = [
857
+ `dsh-superagent doctor${result.version ? ` ${result.version}` : ''}`,
858
+ `node v${result.nodeVersion} · ${process.platform}`,
859
+ `package: ${result.targetDir}`,
860
+ result.profileDir
861
+ ? `profile: ${result.profileDir}`
862
+ : 'profile: not specified (pass --profile <name> to check a DSH profile)',
863
+ '',
864
+ ]
865
+ for (const item of result.checks) {
866
+ lines.push(`${paint(STATUS_COLOR[item.status], `[${STATUS_LABEL[item.status]}]`)} ${item.title}`)
867
+ for (const detail of item.detail ?? []) lines.push(` ${detail}`)
868
+ if (item.fix) {
869
+ lines.push(' fix:')
870
+ for (const fixLine of item.fix.split('\n')) lines.push(` ${fixLine}`)
871
+ }
872
+ }
873
+ const { pass, warn, fail } = result.counts
874
+ lines.push('', `${fail} failed, ${warn} warning(s), ${pass} passed`)
875
+ lines.push(fail === 0
876
+ ? 'no blocking problem found: this copy matches what it claims to be'
877
+ : 'blocking checks failed; run the fix lines above, then re-run doctor')
878
+ return lines.join('\n')
879
+ }