@mawesome/npm-vm 0.0.0-alpha.0 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +50 -1
- package/dist/cli.js +4157 -0
- package/dist/cli.js.map +1 -0
- package/dist/index-B071ZJDk.d.cts +164 -0
- package/dist/index-B071ZJDk.d.ts +164 -0
- package/dist/index.cjs +7 -0
- package/dist/index.d.cts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/internal.cjs +2709 -0
- package/dist/internal.cjs.map +1 -0
- package/dist/internal.d.cts +139 -0
- package/dist/internal.d.ts +139 -0
- package/dist/internal.js +2706 -0
- package/dist/internal.js.map +1 -0
- package/dist/provenance--sOYCeF2.js +322 -0
- package/dist/provenance--sOYCeF2.js.map +1 -0
- package/dist/provenance-DDegWCyS.js +2 -0
- package/dist/runtime/atomic-C3shKdH9.cjs +88 -0
- package/dist/runtime/bootstrap.cjs +271 -0
- package/dist/runtime/commonjs-AANzyd21.cjs +7393 -0
- package/dist/runtime/dispatch-B9OSfqsn.cjs +25156 -0
- package/dist/runtime/dist-CXwBT6rE.cjs +30766 -0
- package/dist/runtime/home-BaoZZSBy.cjs +91 -0
- package/dist/runtime/install-C_M5WK98.cjs +13598 -0
- package/dist/runtime/journal-_bs-eJRJ.cjs +282 -0
- package/dist/runtime/launchers/cmd.tmpl +2 -0
- package/dist/runtime/launchers/ps1.tmpl +5 -0
- package/dist/runtime/launchers/sh.tmpl +3 -0
- package/dist/runtime/lease-HBD4CmBx.cjs +224 -0
- package/dist/runtime/lock-DBeYN-Zg.cjs +141 -0
- package/dist/runtime/messages-vUDkl1-0.cjs +174 -0
- package/dist/runtime/p-map-b8pXdaFZ.cjs +105 -0
- package/dist/runtime/proc-hB8N9WjN.cjs +127 -0
- package/dist/runtime/provenance-B4bajGXQ.cjs +2 -0
- package/dist/runtime/rolldown-runtime-BGT596CS.cjs +64 -0
- package/dist/runtime/runtime.cjs +143 -0
- package/dist/runtime/src-SpeGbMJx.cjs +314 -0
- package/dist/src-Bc9nN1Kl.cjs +2125 -0
- package/dist/src-Bc9nN1Kl.cjs.map +1 -0
- package/dist/src-NhNG2mnQ.js +1798 -0
- package/dist/src-NhNG2mnQ.js.map +1 -0
- package/package.json +87 -17
- package/index.js +0 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"internal.js","names":["forget","run","describe"],"sources":["../src/setup/shims.ts","../src/setup/shell.ts","../src/state/meta.ts","../src/state/journal.ts","../src/state/lock.ts","../src/commands/cache.ts","../src/commands/context.ts","../src/setup/link.ts","../src/setup/layout.ts","../src/setup/profile.ts","../src/setup/windows.ts","../src/commands/doctor.ts","../src/commands/pin.ts","../src/install/provenance.ts","../src/commands/self-update.ts","../src/commands/setup.ts","../src/commands/uninstall.ts","../src/commands/dispatch.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { join, posix, win32 } from 'node:path';\nimport { EXIT, NpmVmError } from '../errors.ts';\n\n/** The launcher ABI the shims carry; a runtime declares the ABI it needs (spec RUN-2). */\nexport const SHIM_ABI = 1;\n\nexport const SHIM_DIR = 'shims';\nexport const LAUNCHERS_DIR = 'launchers';\nexport const SELECTORS = ['npm', 'npx', 'npm-vm'] as const;\nexport type ShimName = (typeof SELECTORS)[number];\n\nexport interface ShimFile {\n\t/** File name inside `shims/`, with the Windows extension where there is one. */\n\tname: string;\n\tcontent: string;\n\tmode: number;\n}\n\nconst UNSAFE = /[\\n\\r\"'`$%!]/;\n\n/** Refuses a home no quoting makes safe in all four shells and cmd (spec SET-2, M-HOMEPATH). */\nexport function assertSafeHome(home: string): void {\n\tconst match = UNSAFE.exec(home);\n\tif (match !== null) {\n\t\tconst shown = match[0] === '\\n' || match[0] === '\\r' ? 'a line break' : `\"${match[0]}\"`;\n\t\tthrow new NpmVmError(\n\t\t\t'M-HOMEPATH',\n\t\t\tEXIT.usage,\n\t\t\t`The npm-vm home ${home} contains ${shown}, which cannot be quoted safely in every shell. Set NPM_VM_HOME to a plain path and run setup again.`,\n\t\t);\n\t}\n}\n\nfunction selectorOf(name: ShimName): 'npm' | 'npx' | 'cli' {\n\treturn name === 'npm-vm' ? 'cli' : name;\n}\n\n/**\n * The launcher templates shipped beside this code: `src/launchers/` from source, `dist/runtime/launchers/`\n * from the bin, and `launchers/` beside an installed `runtime.cjs`.\n */\nexport function templatesDir(): string {\n\tconst here = import.meta.dirname;\n\tfor (const candidate of [\n\t\tjoin(here, LAUNCHERS_DIR),\n\t\tjoin(here, '..', LAUNCHERS_DIR),\n\t\tjoin(here, 'runtime', LAUNCHERS_DIR),\n\t]) {\n\t\tif (existsSync(join(candidate, 'sh.tmpl'))) {\n\t\t\treturn candidate;\n\t\t}\n\t}\n\tthrow new Error(`npm-vm launcher templates not found near ${here}`);\n}\n\nexport type TemplateKind = 'sh' | 'cmd' | 'ps1';\n\nexport function readTemplate(dir: string, kind: TemplateKind): string {\n\t// cmd and ps1 keep their CRLF; an autocrlf checkout must not hand the sh shim CRLF.\n\tconst text = readFileSync(join(dir, `${kind}.tmpl`), 'utf8');\n\treturn kind === 'sh' ? text.replace(/\\r\\n/g, '\\n') : text;\n}\n\n/** Fills one launcher template; the ABI comes from the launcher generation the templates belong to. */\nexport function renderTemplate(\n\ttemplate: string,\n\tvalues: { bootstrap: string; selector: string; abi: number },\n): string {\n\treturn template\n\t\t.replace(/\\{\\{ABI\\}\\}/g, String(values.abi))\n\t\t.replace(/\\{\\{BOOTSTRAP\\}\\}/g, values.bootstrap)\n\t\t.replace(/\\{\\{SELECTOR\\}\\}/g, values.selector);\n}\n\n/** The POSIX shim: `sh` on every OS, so Git Bash and MSYS on Windows get one too. */\nexport function posixShim(\n\thome: string,\n\tname: ShimName,\n\ttemplates: string = templatesDir(),\n\tabi: number = SHIM_ABI,\n\tplatform: NodeJS.Platform = process.platform,\n): string {\n\t// Git Bash passes a backslash path through to node; everywhere else the shim must keep forward slashes.\n\tconst { join: joinPath } = platform === 'win32' ? win32 : posix;\n\treturn renderTemplate(readTemplate(templates, 'sh'), {\n\t\tbootstrap: joinPath(home, 'bootstrap.cjs'),\n\t\tselector: selectorOf(name),\n\t\tabi,\n\t});\n}\n\n/**\n * The cmd shim resolves node.exe through PATH only (`%~$PATH:i`): cmd would otherwise run a `node.exe`\n * committed to the current directory. One command line, so `%*` keeps its quoting.\n */\nexport function cmdShim(\n\thome: string,\n\tname: ShimName,\n\ttemplates: string = templatesDir(),\n\tabi: number = SHIM_ABI,\n): string {\n\treturn renderTemplate(readTemplate(templates, 'cmd'), {\n\t\tbootstrap: win32.join(home, 'bootstrap.cjs'),\n\t\tselector: selectorOf(name),\n\t\tabi,\n\t});\n}\n\n/** PowerShell never searches the current directory for a command, so `Get-Command` is enough. */\nexport function powershellShim(\n\thome: string,\n\tname: ShimName,\n\ttemplates: string = templatesDir(),\n\tabi: number = SHIM_ABI,\n): string {\n\treturn renderTemplate(readTemplate(templates, 'ps1'), {\n\t\tbootstrap: win32.join(home, 'bootstrap.cjs'),\n\t\tselector: selectorOf(name),\n\t\tabi,\n\t});\n}\n\nexport interface RenderOptions {\n\tpowershell?: boolean;\n\ttemplates?: string;\n\tabi?: number;\n}\n\n/** Every shim file for the platform (spec SET-2); `.ps1` files are included only when the policy allows them (WIN-2). */\nexport function renderShims(\n\thome: string,\n\tplatform: NodeJS.Platform,\n\toptions: RenderOptions = {},\n): ShimFile[] {\n\tassertSafeHome(home);\n\tconst templates = options.templates ?? templatesDir();\n\tconst abi = options.abi ?? SHIM_ABI;\n\tconst files: ShimFile[] = [];\n\tfor (const name of SELECTORS) {\n\t\tfiles.push({ name, content: posixShim(home, name, templates, abi, platform), mode: 0o755 });\n\t\tif (platform === 'win32') {\n\t\t\tfiles.push({\n\t\t\t\tname: `${name}.cmd`,\n\t\t\t\tcontent: cmdShim(home, name, templates, abi),\n\t\t\t\tmode: 0o644,\n\t\t\t});\n\t\t\tif (options.powershell !== false) {\n\t\t\t\tfiles.push({\n\t\t\t\t\tname: `${name}.ps1`,\n\t\t\t\t\tcontent: powershellShim(home, name, templates, abi),\n\t\t\t\t\tmode: 0o644,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\treturn files;\n}\n\n/** The ABI a shim or bootstrap file declares, or null when the file is not ours. */\nexport function shimAbi(content: string): number | null {\n\tconst match = /npm-vm launcher abi=(\\d+)|LAUNCHER_ABI = (\\d+)/.exec(content);\n\treturn match === null ? null : Number(match[1] ?? match[2]);\n}\n\nexport function shimDir(home: string): string {\n\treturn join(home, SHIM_DIR);\n}\n\n/** Our `.ps1` shims left from a permissive policy; PowerShell would still prefer them over `.cmd` (WIN-2). */\nexport function stalePowershellShims(home: string): string[] {\n\treturn SELECTORS.map((name) => join(shimDir(home), `${name}.ps1`)).filter((file) => {\n\t\ttry {\n\t\t\treturn shimAbi(readFileSync(file, 'utf8')) !== null;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t});\n}\n","import { win32 } from 'node:path';\nimport { assertSafeHome, SHIM_DIR, shimDir } from './shims.ts';\n\nexport const SHELLS = ['zsh', 'bash', 'fish', 'powershell'] as const;\nexport type Shell = (typeof SHELLS)[number];\n\nexport function isShell(value: string): value is Shell {\n\treturn (SHELLS as readonly string[]).includes(value);\n}\n\nexport const BLOCK_START = '# >>> npm-vm >>>';\nexport const BLOCK_END = '# <<< npm-vm <<<';\n\n/** Escapes a path for use inside a bash or zsh `${var//pattern/}` pattern, where `/` and glob characters are special. */\nfunction patternOf(path: string): string {\n\treturn path.replace(/[\\\\/*?[\\]]/g, (char) => `\\\\${char}`);\n}\n\n/** Adds `shims/` to the front of PATH when absent; sourcing it twice changes nothing (spec SH-1). */\nfunction shimsFor(shell: Shell, home: string): string {\n\tif (shell === 'powershell') {\n\t\treturn win32.join(home, SHIM_DIR);\n\t}\n\t// POSIX shells on Windows (Git Bash, MSYS) take forward slashes; a backslash would escape.\n\treturn process.platform === 'win32' ? shimDir(home).replace(/\\\\/g, '/') : shimDir(home);\n}\n\nexport function pathSnippet(shell: Shell, home: string): string {\n\tassertSafeHome(home);\n\tconst shims = shimsFor(shell, home);\n\tswitch (shell) {\n\t\tcase 'zsh':\n\t\tcase 'bash':\n\t\t\treturn [\n\t\t\t\t`case \":$PATH:\" in`,\n\t\t\t\t` *\":${shims}:\"*) ;;`,\n\t\t\t\t` *) export PATH=\"${shims}:$PATH\" ;;`,\n\t\t\t\t'esac',\n\t\t\t\t'',\n\t\t\t].join('\\n');\n\t\tcase 'fish':\n\t\t\treturn [\n\t\t\t\t`if not contains -- \"${shims}\" $PATH`,\n\t\t\t\t` set -gx PATH \"${shims}\" $PATH`,\n\t\t\t\t'end',\n\t\t\t\t'',\n\t\t\t].join('\\n');\n\t\tcase 'powershell':\n\t\t\treturn [\n\t\t\t\t`if (($env:Path -split [IO.Path]::PathSeparator) -notcontains '${shims}') {`,\n\t\t\t\t` $env:Path = '${shims}' + [IO.Path]::PathSeparator + $env:Path`,\n\t\t\t\t'}',\n\t\t\t\t'',\n\t\t\t].join('\\n');\n\t}\n}\n\n/**\n * The prompt hook (spec SH-2): moves `shims/` back to the front when something prepended over it,\n * with parameter expansion only, keeping `$?` and chaining whatever hook was there.\n */\nexport function hookSnippet(shell: Shell, home: string): string {\n\tassertSafeHome(home);\n\tconst shims = shimsFor(shell, home);\n\tswitch (shell) {\n\t\tcase 'zsh':\n\t\t\treturn [\n\t\t\t\t'_npm_vm_guard() {',\n\t\t\t\t' local ret=$?',\n\t\t\t\t` if [[ \"$path[1]\" != \"${shims}\" ]]; then`,\n\t\t\t\t` path=(\"${shims}\" \\${path:#${shims}})`,\n\t\t\t\t' fi',\n\t\t\t\t' return $ret',\n\t\t\t\t'}',\n\t\t\t\t'if [[ -z \"${precmd_functions[(r)_npm_vm_guard]}\" ]]; then',\n\t\t\t\t' precmd_functions+=(_npm_vm_guard)',\n\t\t\t\t'fi',\n\t\t\t\t'',\n\t\t\t].join('\\n');\n\t\tcase 'bash':\n\t\t\treturn [\n\t\t\t\t'_npm_vm_guard() {',\n\t\t\t\t' local ret=$?',\n\t\t\t\t` case \":$PATH:\" in`,\n\t\t\t\t` \":${shims}:\"*) ;;`,\n\t\t\t\t' *)',\n\t\t\t\t' local rest=\":$PATH:\"',\n\t\t\t\t` rest=\"\\${rest//:${patternOf(shims)}:/:}\"`,\n\t\t\t\t' rest=\"${rest#:}\"',\n\t\t\t\t' rest=\"${rest%:}\"',\n\t\t\t\t` PATH=\"${shims}\\${rest:+:$rest}\"`,\n\t\t\t\t' ;;',\n\t\t\t\t' esac',\n\t\t\t\t' return $ret',\n\t\t\t\t'}',\n\t\t\t\t'case \";${PROMPT_COMMAND};\" in',\n\t\t\t\t' *\";_npm_vm_guard;\"*) ;;',\n\t\t\t\t' *) PROMPT_COMMAND=\"_npm_vm_guard${PROMPT_COMMAND:+;$PROMPT_COMMAND}\" ;;',\n\t\t\t\t'esac',\n\t\t\t\t'',\n\t\t\t].join('\\n');\n\t\tcase 'fish':\n\t\t\treturn [\n\t\t\t\t'if status is-interactive',\n\t\t\t\t' function _npm_vm_guard --on-event fish_prompt',\n\t\t\t\t` if test \"$PATH[1]\" != \"${shims}\"`,\n\t\t\t\t` set -l found (contains -i -- \"${shims}\" $PATH)`,\n\t\t\t\t' if test -n \"$found\"',\n\t\t\t\t' set -e PATH[$found]',\n\t\t\t\t' end',\n\t\t\t\t` set -gx PATH \"${shims}\" $PATH`,\n\t\t\t\t' end',\n\t\t\t\t' end',\n\t\t\t\t'end',\n\t\t\t\t'',\n\t\t\t].join('\\n');\n\t\tcase 'powershell':\n\t\t\treturn [\n\t\t\t\t'if (-not (Test-Path Function:\\\\global:_npm_vm_original_prompt)) {',\n\t\t\t\t' $prev = Get-Item Function:\\\\prompt -ErrorAction SilentlyContinue',\n\t\t\t\t' if ($prev) { Set-Item Function:\\\\global:_npm_vm_original_prompt $prev.ScriptBlock }',\n\t\t\t\t' else { function global:_npm_vm_original_prompt { \"PS $($executionContext.SessionState.Path.CurrentLocation)$(\\'>\\' * ($nestedPromptLevel + 1)) \" } }',\n\t\t\t\t' function global:prompt {',\n\t\t\t\t' $ok = $?',\n\t\t\t\t' $exit = $global:LASTEXITCODE',\n\t\t\t\t` $shims = '${shims}'`,\n\t\t\t\t' $parts = @($env:Path -split [IO.Path]::PathSeparator)',\n\t\t\t\t' if ($parts.Length -eq 0 -or $parts[0] -ne $shims) {',\n\t\t\t\t' $env:Path = (@($shims) + @($parts | Where-Object { $_ -ne $shims })) -join [IO.Path]::PathSeparator',\n\t\t\t\t' }',\n\t\t\t\t' $out = & $function:global:_npm_vm_original_prompt',\n\t\t\t\t' $global:LASTEXITCODE = $exit',\n\t\t\t\t' $out',\n\t\t\t\t\" if (-not $ok) { Write-Error 'npm-vm: preserving $?' -ErrorAction SilentlyContinue }\",\n\t\t\t\t' }',\n\t\t\t\t'}',\n\t\t\t\t'',\n\t\t\t].join('\\n');\n\t}\n}\n\n/** Both snippets inside the marked block `setup` writes and `uninstall` removes (spec SH-4). */\nexport function profileBlock(\n\tshell: Shell,\n\thome: string,\n\tparts: { path: boolean; hook: boolean },\n): string {\n\tconst body = [\n\t\tparts.path ? pathSnippet(shell, home) : '',\n\t\tparts.hook ? hookSnippet(shell, home) : '',\n\t]\n\t\t.filter((text) => text !== '')\n\t\t.join('');\n\treturn `${BLOCK_START}\\n${body}${BLOCK_END}\\n`;\n}\n","import { createHash } from 'node:crypto';\nimport { lstatSync, readFileSync, readlinkSync } from 'node:fs';\n\nexport type FileType = 'file' | 'directory' | 'symlink' | 'other' | 'missing';\nexport type LineEndings = 'lf' | 'crlf' | 'mixed' | 'none';\n\n/** What a target looked like at one moment (spec MUT-4), enough to tell our write from someone else's. */\nexport interface Meta {\n\ttype: FileType;\n\t/** POSIX permission bits; Windows ACLs are left to the OS and recorded as 0. */\n\tmode: number;\n\tsha256: string | null;\n\tencoding: 'utf8' | 'binary' | null;\n\tlineEndings: LineEndings | null;\n\tsymlinkTarget: string | null;\n}\n\nexport function sha256(content: Buffer | string): string {\n\treturn createHash('sha256').update(content).digest('hex');\n}\n\nfunction isUtf8(content: Buffer): boolean {\n\treturn !content.includes(0) && Buffer.from(content.toString('utf8'), 'utf8').equals(content);\n}\n\nexport function lineEndingsOf(text: string): LineEndings {\n\tconst crlf = (text.match(/\\r\\n/g) ?? []).length;\n\tconst lf = (text.match(/\\n/g) ?? []).length - crlf;\n\tif (crlf === 0 && lf === 0) {\n\t\treturn 'none';\n\t}\n\tif (crlf > 0 && lf > 0) {\n\t\treturn 'mixed';\n\t}\n\treturn crlf > 0 ? 'crlf' : 'lf';\n}\n\nexport const MISSING: Meta = {\n\ttype: 'missing',\n\tmode: 0,\n\tsha256: null,\n\tencoding: null,\n\tlineEndings: null,\n\tsymlinkTarget: null,\n};\n\n/** Captures `path` without following symlinks; a missing path is a valid state, not an error. */\nexport function captureMeta(path: string): Meta {\n\tlet stat;\n\ttry {\n\t\tstat = lstatSync(path);\n\t} catch {\n\t\treturn MISSING;\n\t}\n\tconst mode = process.platform === 'win32' ? 0 : stat.mode & 0o7777;\n\tif (stat.isSymbolicLink()) {\n\t\treturn {\n\t\t\ttype: 'symlink',\n\t\t\tmode,\n\t\t\tsha256: null,\n\t\t\tencoding: null,\n\t\t\tlineEndings: null,\n\t\t\tsymlinkTarget: readlinkSync(path),\n\t\t};\n\t}\n\tif (stat.isDirectory()) {\n\t\treturn {\n\t\t\ttype: 'directory',\n\t\t\tmode,\n\t\t\tsha256: null,\n\t\t\tencoding: null,\n\t\t\tlineEndings: null,\n\t\t\tsymlinkTarget: null,\n\t\t};\n\t}\n\tif (!stat.isFile()) {\n\t\treturn {\n\t\t\ttype: 'other',\n\t\t\tmode,\n\t\t\tsha256: null,\n\t\t\tencoding: null,\n\t\t\tlineEndings: null,\n\t\t\tsymlinkTarget: null,\n\t\t};\n\t}\n\tconst content = readFileSync(path);\n\tconst utf8 = isUtf8(content);\n\treturn {\n\t\ttype: 'file',\n\t\tmode,\n\t\tsha256: sha256(content),\n\t\tencoding: utf8 ? 'utf8' : 'binary',\n\t\tlineEndings: utf8 ? lineEndingsOf(content.toString('utf8')) : null,\n\t\tsymlinkTarget: null,\n\t};\n}\n\n/** Whether the path still holds exactly what `meta` recorded (spec MUT-5): same type, same bytes or link target. */\nexport function metaMatches(path: string, meta: Meta): boolean {\n\tconst now = captureMeta(path);\n\treturn (\n\t\tnow.type === meta.type && now.sha256 === meta.sha256 && now.symlinkTarget === meta.symlinkTarget\n\t);\n}\n","import {\n\tcopyFileSync,\n\texistsSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trmSync,\n\tunlinkSync,\n} from 'node:fs';\nimport { join } from 'node:path';\nimport { atomicWrite, removeWithRetry, withSharingRetry } from './atomic.ts';\nimport { newToken, type OwnerRecord } from './lease.ts';\nimport { captureMeta, metaMatches, sha256, type Meta } from './meta.ts';\nimport { isLive } from './proc.ts';\n\nexport type JournalKind = 'launcher' | 'profile' | 'link' | 'home' | 'project';\n\n/** A pending change to one file (spec MUT-2): enough to finish it or undo it after a crash. */\nexport interface Journal {\n\tid: string;\n\tkind: JournalKind;\n\towner: OwnerRecord;\n\ttarget: string;\n\toriginal: Meta;\n\t/** The sha256 the target will have, or null when the change deletes it. */\n\tintended: string | null;\n\t/** Staged copy of the new content, beside the journal. */\n\tstaged: string | null;\n\t/** Backup of the original content, beside the journal; null when there was none. */\n\tbackup: string | null;\n\tmode: number;\n\tcreatedAt: string;\n}\n\nexport interface RecoveryReport {\n\tfinished: string[];\n\treplayed: string[];\n\trolledBack: string[];\n\tchanged: string[];\n\tskipped: string[];\n}\n\nexport function journalPath(journalDir: string, id: string): string {\n\treturn join(journalDir, `${id}.json`);\n}\n\nexport function readJournal(file: string): Journal | null {\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(file, 'utf8')) as Journal;\n\t\treturn typeof parsed.id === 'string' && typeof parsed.target === 'string' ? parsed : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function listJournals(journalDir: string): Journal[] {\n\tlet names: string[];\n\ttry {\n\t\tnames = readdirSync(journalDir);\n\t} catch {\n\t\treturn [];\n\t}\n\treturn names\n\t\t.filter((name) => name.endsWith('.json'))\n\t\t.map((name) => readJournal(join(journalDir, name)))\n\t\t.filter((journal): journal is Journal => journal !== null);\n}\n\nexport function hasJournals(journalDir: string): boolean {\n\treturn listJournals(journalDir).length > 0;\n}\n\n/**\n * Applies one file change under a journal: backup and staged copy first, the journal, then the write.\n * The journal and its sidecars disappear only after the target holds the intended bytes.\n */\nexport function mutateFile(\n\tjournalDir: string,\n\tkind: JournalKind,\n\towner: OwnerRecord,\n\ttarget: string,\n\tcontent: Buffer | null,\n\tmode = 0o644,\n): void {\n\tmkdirSync(journalDir, { recursive: true, mode: 0o700 });\n\tconst id = `${kind}-${newToken()}`;\n\tconst original = captureMeta(target);\n\tlet backup: string | null = null;\n\tif (original.type === 'file') {\n\t\tbackup = join(journalDir, `${id}.bak`);\n\t\tcopyFileSync(target, backup);\n\t}\n\tlet staged: string | null = null;\n\tif (content !== null) {\n\t\tstaged = join(journalDir, `${id}.new`);\n\t\tatomicWrite(staged, content, 0o600);\n\t}\n\tconst journal: Journal = {\n\t\tid,\n\t\tkind,\n\t\towner,\n\t\ttarget,\n\t\toriginal,\n\t\tintended: content === null ? null : sha256(content),\n\t\tstaged,\n\t\tbackup,\n\t\tmode,\n\t\tcreatedAt: new Date().toISOString(),\n\t};\n\tatomicWrite(journalPath(journalDir, id), JSON.stringify(journal), 0o600);\n\tapply(journal, content);\n\tdiscard(journalDir, journal);\n}\n\nfunction apply(journal: Journal, content: Buffer | null): void {\n\tif (content === null) {\n\t\twithSharingRetry(() => {\n\t\t\tif (existsSync(journal.target)) {\n\t\t\t\tunlinkSync(journal.target);\n\t\t\t}\n\t\t});\n\t\treturn;\n\t}\n\tatomicWrite(journal.target, content, journal.mode);\n}\n\nfunction discard(journalDir: string, journal: Journal): void {\n\tfor (const sidecar of [journal.backup, journal.staged]) {\n\t\tif (sidecar !== null) {\n\t\t\trmSync(sidecar, { force: true });\n\t\t}\n\t}\n\trmSync(journalPath(journalDir, journal.id), { force: true });\n}\n\nfunction targetSha(target: string): string | null {\n\tconst meta = captureMeta(target);\n\treturn meta.type === 'file' ? meta.sha256 : null;\n}\n\n/**\n * Finishes one journal (spec MUT-2): a target already at the intended bytes is done; one still at the\n * original is replayed from the staged copy; anything else is left alone and reported as changed (MUT-5).\n */\nexport function recoverJournal(journalDir: string, journal: Journal, report: RecoveryReport): void {\n\tconst current = targetSha(journal.target);\n\tconst exists = captureMeta(journal.target).type !== 'missing';\n\tif (journal.intended === null ? !exists : current === journal.intended) {\n\t\tdiscard(journalDir, journal);\n\t\treport.finished.push(journal.id);\n\t\treturn;\n\t}\n\tif (metaMatches(journal.target, journal.original)) {\n\t\tif (journal.intended === null) {\n\t\t\tapply(journal, null);\n\t\t\treport.replayed.push(journal.id);\n\t\t} else if (\n\t\t\tjournal.staged !== null &&\n\t\t\texistsSync(journal.staged) &&\n\t\t\tsha256(readFileSync(journal.staged)) === journal.intended\n\t\t) {\n\t\t\tapply(journal, readFileSync(journal.staged));\n\t\t\treport.replayed.push(journal.id);\n\t\t} else {\n\t\t\t// Nothing to replay from, and the target is untouched: the change simply never happened.\n\t\t\treport.rolledBack.push(journal.id);\n\t\t}\n\t\tdiscard(journalDir, journal);\n\t\treturn;\n\t}\n\t// Writes are atomic renames, so a target matching neither side was changed by someone else: leave it.\n\treport.changed.push(journal.target);\n\tdiscard(journalDir, journal);\n}\n\n/** Recovers every journal whose owner is dead on this machine; foreign and live ones are skipped. */\nexport function recoverDeadJournals(\n\tjournalDir: string,\n\tmachineId: string,\n\tkinds?: readonly JournalKind[],\n): RecoveryReport {\n\tconst report: RecoveryReport = {\n\t\tfinished: [],\n\t\treplayed: [],\n\t\trolledBack: [],\n\t\tchanged: [],\n\t\tskipped: [],\n\t};\n\tfor (const journal of listJournals(journalDir)) {\n\t\tif (kinds !== undefined && !kinds.includes(journal.kind)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (journal.owner.machineId !== machineId || isLive(journal.owner)) {\n\t\t\treport.skipped.push(journal.id);\n\t\t\tcontinue;\n\t\t}\n\t\trecoverJournal(journalDir, journal, report);\n\t}\n\treturn report;\n}\n\n/** Recovers one journal the operator vouched for, whatever machine owns it (the `recover` command). */\nexport function recoverForeignJournal(\n\tjournalDir: string,\n\tid: string,\n\tconfirmedMachineId: string,\n): RecoveryReport {\n\tconst report: RecoveryReport = {\n\t\tfinished: [],\n\t\treplayed: [],\n\t\trolledBack: [],\n\t\tchanged: [],\n\t\tskipped: [],\n\t};\n\tconst journal = readJournal(journalPath(journalDir, id));\n\tif (journal === null) {\n\t\tthrow new Error(`no journal ${id} in ${journalDir}`);\n\t}\n\tif (journal.owner.machineId !== confirmedMachineId) {\n\t\tthrow new Error(\n\t\t\t`journal ${id} belongs to machine ${journal.owner.machineId}, not ${confirmedMachineId}`,\n\t\t);\n\t}\n\trecoverJournal(journalDir, journal, report);\n\treturn report;\n}\n\nexport function removeJournalDir(journalDir: string): void {\n\tremoveWithRetry(journalDir);\n}\n","import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { EXIT, NpmVmError } from '../errors.ts';\nimport { lockedMessage } from '../messages.ts';\nimport { newToken, type OwnerRecord } from './lease.ts';\nimport { isLive } from './proc.ts';\n\nexport const LOCK_FILE = 'lock';\nconst WAIT_LIMIT_MS = 10_000;\n\n/** What the lock file records: the owner plus a token only the owner knows, so only it can release. */\nexport interface LockRecord extends OwnerRecord {\n\ttoken: string;\n}\n\nexport interface Lock {\n\tpath: string;\n\trelease(): void;\n}\n\nexport function lockPath(stateDir: string): string {\n\treturn join(stateDir, LOCK_FILE);\n}\n\nexport function readLock(stateDir: string): LockRecord | null {\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(lockPath(stateDir), 'utf8')) as Partial<LockRecord>;\n\t\tif (typeof parsed.pid !== 'number' || typeof parsed.token !== 'string') {\n\t\t\treturn null;\n\t\t}\n\t\treturn {\n\t\t\tpid: parsed.pid,\n\t\t\tstart: typeof parsed.start === 'string' ? parsed.start : null,\n\t\t\thost: typeof parsed.host === 'string' ? parsed.host : '?',\n\t\t\tmachineId: typeof parsed.machineId === 'string' ? parsed.machineId : '?',\n\t\t\tcreatedAt: typeof parsed.createdAt === 'string' ? parsed.createdAt : '',\n\t\t\ttoken: parsed.token,\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Whether the lock owner can be shown to be dead: only on this machine, and only by PROC-1. */\nexport function lockOwnerLive(record: LockRecord | null, machineId: string): boolean {\n\tif (record === null) {\n\t\treturn true;\n\t}\n\tif (record.machineId !== machineId) {\n\t\treturn true;\n\t}\n\treturn isLive(record);\n}\n\nfunction tryCreate(path: string, record: LockRecord): boolean {\n\ttry {\n\t\twriteFileSync(path, JSON.stringify(record), { flag: 'wx', mode: 0o600 });\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === 'EEXIST') {\n\t\t\treturn false;\n\t\t}\n\t\t// A half-written lock would block everyone with no owner to release it.\n\t\trmSync(path, { force: true });\n\t\tthrow error;\n\t}\n\treturn true;\n}\n\nfunction sleep(ms: number): Promise<void> {\n\treturn new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Takes the exclusive lock (spec MUT-1): created with O_EXCL, released only by its owner, never reclaimed.\n * Waits with backoff for up to 10 s, then fails with M-LOCKED naming the file and whether the owner is live.\n */\nexport async function acquireLock(\n\tstateDir: string,\n\towner: OwnerRecord,\n\toptions: { waitMs?: number } = {},\n): Promise<Lock> {\n\tmkdirSync(stateDir, { recursive: true, mode: 0o700 });\n\tconst path = lockPath(stateDir);\n\tconst record: LockRecord = { ...owner, token: newToken() };\n\tconst deadline = Date.now() + (options.waitMs ?? WAIT_LIMIT_MS);\n\tlet delay = 50;\n\tfor (;;) {\n\t\tif (tryCreate(path, record)) {\n\t\t\treturn {\n\t\t\t\tpath,\n\t\t\t\trelease() {\n\t\t\t\t\t// Only the owner removes the lock, and only while the file still carries its token.\n\t\t\t\t\tif (readLock(stateDir)?.token === record.token) {\n\t\t\t\t\t\trmSync(path, { force: true });\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (Date.now() + delay > deadline) {\n\t\t\tconst holder = readLock(stateDir);\n\t\t\tconst foreign = holder !== null && holder.machineId !== owner.machineId;\n\t\t\tconst live = lockOwnerLive(holder, owner.machineId);\n\t\t\tthrow new NpmVmError('M-LOCKED', EXIT.problems, lockedMessage(path, holder, live, foreign));\n\t\t}\n\t\tawait sleep(delay);\n\t\tdelay = Math.min(delay * 2, 1000);\n\t}\n}\n\n/** One attempt, no waiting; for the launcher's recovery check, which must never delay npm. */\nexport function tryLock(stateDir: string, owner: OwnerRecord): Lock | null {\n\tmkdirSync(stateDir, { recursive: true, mode: 0o700 });\n\tconst path = lockPath(stateDir);\n\tconst record: LockRecord = { ...owner, token: newToken() };\n\tif (!tryCreate(path, record)) {\n\t\treturn null;\n\t}\n\treturn {\n\t\tpath,\n\t\trelease() {\n\t\t\tif (readLock(stateDir)?.token === record.token) {\n\t\t\t\trmSync(path, { force: true });\n\t\t\t}\n\t\t},\n\t};\n}\n","import { EXIT, NpmVmError } from '../errors.ts';\nimport { resolveNpmWith } from '../index.ts';\nimport { listEntries } from '../install/cache.ts';\nimport { createContext, createInstaller } from '../install/index.ts';\nimport { readVerified } from '../install/verify.ts';\nimport { listJournals, recoverDeadJournals, recoverForeignJournal } from '../state/journal.ts';\nimport { listLeases, ownerLive } from '../state/lease.ts';\nimport { acquireLock } from '../state/lock.ts';\nimport { isLive } from '../state/proc.ts';\nimport { lastUsed, pruneCache, type PruneReport } from '../state/prune.ts';\nimport type { CommandContext } from './context.ts';\n\nconst DAY_MS = 86_400_000;\nexport const DEFAULT_PRUNE_DAYS = 90;\n\n/** `install [<spec>]`: fetches and verifies the project's npm, or the given spec, into the cache. */\nexport async function install(\n\tcontext: CommandContext,\n\tspec: string | undefined,\n\tcwd: string = process.cwd(),\n): Promise<number> {\n\tconst env = spec === undefined ? context.env : { ...context.env, NPM_VM_VERSION: spec };\n\tconst installer = createInstaller(createContext(env, context.dirs.home));\n\tconst result = await resolveNpmWith([], cwd, { env }, installer);\n\tif (result.selection === null) {\n\t\tcontext.io.out(\n\t\t\tcontext.json\n\t\t\t\t? JSON.stringify(result)\n\t\t\t\t: `Node's own npm ${result.version} satisfies the requirement; nothing to download.`,\n\t\t);\n\t\treturn EXIT.ok;\n\t}\n\tconst ensured = await installer.ensure(result.selection);\n\tensured.lease.release();\n\tcontext.io.out(\n\t\tcontext.json\n\t\t\t? JSON.stringify({ ...result, entryPath: ensured.entryPath })\n\t\t\t: `npm ${result.version} is ready in ${ensured.entryPath}`,\n\t);\n\treturn EXIT.ok;\n}\n\nexport interface CacheEntryView {\n\tversion: string;\n\tintegrity: string;\n\tpath: string;\n\tlastUsed: string | null;\n\tliveLeases: number;\n\tverifiedAt: string;\n}\n\nexport function cacheList(context: CommandContext): number {\n\tconst entries: CacheEntryView[] = listEntries(context.dirs.cache).map((entry) => {\n\t\tconst used = lastUsed(entry.entryPath as string);\n\t\treturn {\n\t\t\tversion: entry.version,\n\t\t\tintegrity: entry.integrity,\n\t\t\tpath: entry.entryPath as string,\n\t\t\tlastUsed: used === null ? null : new Date(used).toISOString(),\n\t\t\tliveLeases: listLeases(entry.entryPath as string).filter((lease) => ownerLive(lease)).length,\n\t\t\tverifiedAt: readVerified(entry.entryPath as string)?.verifiedAt ?? '',\n\t\t};\n\t});\n\tif (context.json) {\n\t\tcontext.io.out(JSON.stringify({ cache: context.dirs.cache, entries }, null, 2));\n\t} else {\n\t\tconst lines = [`${context.dirs.cache}`];\n\t\tfor (const entry of entries) {\n\t\t\tlines.push(\n\t\t\t\t` npm ${entry.version} ${entry.path} last used ${entry.lastUsed ?? 'never'}${entry.liveLeases > 0 ? ` in use by ${entry.liveLeases}` : ''}`,\n\t\t\t);\n\t\t}\n\t\tif (entries.length === 0) {\n\t\t\tlines.push(' (empty)');\n\t\t}\n\t\tcontext.io.out(lines.join('\\n'));\n\t}\n\treturn EXIT.ok;\n}\n\nexport async function cachePrune(\n\tcontext: CommandContext,\n\tolderThanDays: number = DEFAULT_PRUNE_DAYS,\n): Promise<number> {\n\tif (!Number.isFinite(olderThanDays) || olderThanDays < 0) {\n\t\tthrow new NpmVmError(\n\t\t\t'M-NOMATCH',\n\t\t\tEXIT.usage,\n\t\t\t'--older-than needs a non-negative number of days.',\n\t\t);\n\t}\n\tconst lock = await acquireLock(context.dirs.state, context.owner);\n\ttry {\n\t\trecoverDeadJournals(context.dirs.journal, context.dirs.machine.id);\n\t\t// Homes differ, the per-machine cache does not: a lock inside the cache keeps two homes from pruning at once.\n\t\tconst cacheLock = await acquireLock(context.dirs.cache, context.owner);\n\t\tlet report: PruneReport;\n\t\ttry {\n\t\t\treport = pruneCache(context.dirs.cache, context.owner, {\n\t\t\t\tmaxAgeMs: olderThanDays * DAY_MS,\n\t\t\t});\n\t\t} finally {\n\t\t\tcacheLock.release();\n\t\t}\n\t\tcontext.io.out(\n\t\t\tcontext.json\n\t\t\t\t? JSON.stringify(report, null, 2)\n\t\t\t\t: `Removed ${report.removed.length}, kept ${report.kept.length}, skipped ${report.skipped.length} (in use).`,\n\t\t);\n\t} finally {\n\t\tlock.release();\n\t}\n\treturn EXIT.ok;\n}\n\n/** `recover --journal <id> --confirm-dead-machine <machine-id>` (spec PROC-1, CLI). */\nexport async function recover(\n\tcontext: CommandContext,\n\tjournalId: string,\n\tconfirmedMachine: string,\n): Promise<number> {\n\tconst journal = listJournals(context.dirs.journal).find((entry) => entry.id === journalId);\n\tif (journal === undefined) {\n\t\tthrow new NpmVmError(\n\t\t\t'M-NOMATCH',\n\t\t\tEXIT.usage,\n\t\t\t`No journal ${journalId} under ${context.dirs.journal}.`,\n\t\t);\n\t}\n\tif (journal.owner.machineId !== confirmedMachine) {\n\t\tthrow new NpmVmError(\n\t\t\t'M-NOMATCH',\n\t\t\tEXIT.usage,\n\t\t\t`Journal ${journalId} belongs to machine ${journal.owner.machineId}, not ${confirmedMachine}.`,\n\t\t);\n\t}\n\tif (journal.owner.machineId === context.dirs.machine.id && isLive(journal.owner)) {\n\t\tthrow new NpmVmError(\n\t\t\t'M-LOCKED',\n\t\t\tEXIT.problems,\n\t\t\t`Journal ${journalId} belongs to PID ${journal.owner.pid} on this machine, which is still running.`,\n\t\t);\n\t}\n\tconst lock = await acquireLock(context.dirs.state, context.owner);\n\ttry {\n\t\tconst report = recoverForeignJournal(context.dirs.journal, journalId, confirmedMachine);\n\t\tcontext.io.out(\n\t\t\tcontext.json ? JSON.stringify(report) : `Recovered ${journalId}: ${describeReport(report)}`,\n\t\t);\n\t} finally {\n\t\tlock.release();\n\t}\n\treturn EXIT.ok;\n}\n\nfunction describeReport(report: {\n\tfinished: string[];\n\treplayed: string[];\n\trolledBack: string[];\n\tchanged: string[];\n}): string {\n\tif (report.replayed.length > 0) {\n\t\treturn 'replayed';\n\t}\n\tif (report.rolledBack.length > 0) {\n\t\treturn 'rolled back';\n\t}\n\tif (report.changed.length > 0) {\n\t\treturn 'target changed since, left untouched';\n\t}\n\treturn 'already finished';\n}\n","import { createInterface } from 'node:readline/promises';\nimport { resolveDirs, type Dirs } from '../setup/home.ts';\nimport { ownerRecord, type OwnerRecord } from '../state/lease.ts';\n\nexport interface CommandIo {\n\tout(text: string): void;\n\terr(text: string): void;\n\t/** Asks a yes/no question; a non-interactive session answers no. */\n\tconfirm(question: string): Promise<boolean>;\n\tinteractive: boolean;\n}\n\nexport interface CommandContext {\n\tdirs: Dirs;\n\tenv: NodeJS.ProcessEnv;\n\tplatform: NodeJS.Platform;\n\towner: OwnerRecord;\n\tio: CommandIo;\n\tjson: boolean;\n\tversion: string;\n}\n\nexport interface ContextOptions {\n\thome?: string;\n\tenv?: NodeJS.ProcessEnv;\n\tjson?: boolean;\n\tio?: CommandIo;\n\tversion: string;\n}\n\nexport function terminalIo(): CommandIo {\n\tconst interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);\n\treturn {\n\t\tout: (text) => process.stdout.write(`${text}\\n`),\n\t\terr: (text) => process.stderr.write(`${text}\\n`),\n\t\tinteractive,\n\t\tasync confirm(question) {\n\t\t\tif (!interactive) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tconst rl = createInterface({ input: process.stdin, output: process.stdout });\n\t\t\ttry {\n\t\t\t\tconst answer = await rl.question(`${question} [y/N] `);\n\t\t\t\treturn /^y(es)?$/i.test(answer.trim());\n\t\t\t} finally {\n\t\t\t\trl.close();\n\t\t\t}\n\t\t},\n\t};\n}\n\nexport function createCommandContext(options: ContextOptions): CommandContext {\n\tconst env = options.env ?? process.env;\n\tconst dirs = resolveDirs(env, options.home);\n\treturn {\n\t\tdirs,\n\t\tenv,\n\t\tplatform: process.platform,\n\t\towner: ownerRecord(dirs.machine.id),\n\t\tio: options.io ?? terminalIo(),\n\t\tjson: options.json ?? false,\n\t\tversion: options.version,\n\t};\n}\n","import {\n\tcopyFileSync,\n\texistsSync,\n\tlstatSync,\n\treaddirSync,\n\treadFileSync,\n\treadlinkSync,\n\trealpathSync,\n\trenameSync,\n\trmSync,\n\tsymlinkSync,\n} from 'node:fs';\nimport { homedir } from 'node:os';\nimport { basename, dirname, join } from 'node:path';\nimport { atomicWrite, withSharingRetry } from '../state/atomic.ts';\nimport { mutateFile } from '../state/journal.ts';\nimport type { OwnerRecord } from '../state/lease.ts';\nimport { captureMeta, metaMatches, MISSING, type Meta } from '../state/meta.ts';\nimport type { Dirs } from './home.ts';\nimport { cmdShim, posixShim, powershellShim, type ShimName } from './shims.ts';\n\nexport type NodeManager = 'nvm' | 'fnm' | 'nvm-windows';\n\n/** One Node install whose `npm` and `npx` entry points `--link` replaces (spec LNK-1). */\nexport interface NodeInstall {\n\tmanager: NodeManager;\n\tversion: string;\n\tbinDir: string;\n}\n\nexport const ORIGINAL_SUFFIX = '.npm-vm-original';\nexport const LINKS_FILE = 'links.json';\n\nexport interface LinkRecord {\n\tbinDir: string;\n\t/** The entry point we replaced, e.g. `npm` or `npm.cmd`. */\n\tname: string;\n\ttarget: string;\n\toriginalPath: string | null;\n\toriginal: Meta;\n\tshim: Meta;\n\tlinkedAt: string;\n}\n\nexport interface LinksFile {\n\tversion: 1;\n\tentries: LinkRecord[];\n}\n\nfunction versionsUnder(dir: string): string[] {\n\ttry {\n\t\treturn readdirSync(dir).filter((name) => /^v?\\d+\\.\\d+\\.\\d+$/.test(name));\n\t} catch {\n\t\treturn [];\n\t}\n}\n\nfunction fnmDir(env: NodeJS.ProcessEnv, platform: NodeJS.Platform, home: string): string {\n\tif (env['FNM_DIR']) {\n\t\treturn env['FNM_DIR'];\n\t}\n\tif (platform === 'win32') {\n\t\treturn join(env['APPDATA'] ?? join(home, 'AppData', 'Roaming'), 'fnm');\n\t}\n\tif (platform === 'darwin') {\n\t\treturn join(home, 'Library', 'Application Support', 'fnm');\n\t}\n\treturn join(env['XDG_DATA_HOME'] || join(home, '.local', 'share'), 'fnm');\n}\n\n/** The root nvm-windows keeps its versions in, from its settings.txt (spec LNK-1). */\nfunction nvmWindowsRoot(env: NodeJS.ProcessEnv): string | null {\n\tconst nvmHome = env['NVM_HOME'];\n\tif (!nvmHome) {\n\t\treturn null;\n\t}\n\ttry {\n\t\tconst settings = readFileSync(join(nvmHome, 'settings.txt'), 'utf8');\n\t\tconst root = /^root:\\s*(.+)$/m.exec(settings)?.[1]?.trim();\n\t\treturn root ?? nvmHome;\n\t} catch {\n\t\treturn nvmHome;\n\t}\n}\n\n/** Windows paths resolved through junctions and compared without case, so one install is never linked twice (LNK-4). */\nexport function installKey(binDir: string, platform: NodeJS.Platform): string {\n\tlet real = binDir;\n\ttry {\n\t\treal = realpathSync(binDir);\n\t} catch {\n\t\t// A missing dir is listed as given and skipped as unwritable later.\n\t}\n\treturn platform === 'win32' ? real.toLowerCase() : real;\n}\n\nexport function findNodeInstalls(\n\tenv: NodeJS.ProcessEnv = process.env,\n\tplatform: NodeJS.Platform = process.platform,\n\thome: string = env['HOME'] || homedir(),\n): NodeInstall[] {\n\tconst installs: NodeInstall[] = [];\n\tconst seen = new Set<string>();\n\tconst add = (install: NodeInstall): void => {\n\t\tconst key = installKey(install.binDir, platform);\n\t\tif (!seen.has(key) && existsSync(install.binDir)) {\n\t\t\tseen.add(key);\n\t\t\tinstalls.push(install);\n\t\t}\n\t};\n\tconst nvmDir = env['NVM_DIR'] || join(home, '.nvm');\n\tfor (const version of versionsUnder(join(nvmDir, 'versions', 'node'))) {\n\t\tadd({\n\t\t\tmanager: 'nvm',\n\t\t\tversion: version.replace(/^v/, ''),\n\t\t\tbinDir: join(nvmDir, 'versions', 'node', version, 'bin'),\n\t\t});\n\t}\n\tconst fnm = join(fnmDir(env, platform, home), 'node-versions');\n\tfor (const version of versionsUnder(fnm)) {\n\t\tconst installation = join(fnm, version, 'installation');\n\t\tadd({\n\t\t\tmanager: 'fnm',\n\t\t\tversion: version.replace(/^v/, ''),\n\t\t\tbinDir: platform === 'win32' ? installation : join(installation, 'bin'),\n\t\t});\n\t}\n\tif (platform === 'win32') {\n\t\tconst root = nvmWindowsRoot(env);\n\t\tif (root !== null) {\n\t\t\tfor (const version of versionsUnder(root)) {\n\t\t\t\tadd({\n\t\t\t\t\tmanager: 'nvm-windows',\n\t\t\t\t\tversion: version.replace(/^v/, ''),\n\t\t\t\t\tbinDir: join(root, version),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\treturn installs;\n}\n\n/** A file `--link` touches in one install: a shim to write, or `content: null` for a file to move aside (WIN-2). */\nexport interface LinkTarget {\n\tname: string;\n\tcontent: string | null;\n\tmode: number;\n}\n\n/** The files `--link` replaces in one install; blocked `.ps1` files are moved aside so `.cmd` wins. */\nexport function linkTargets(\n\thome: string,\n\tplatform: NodeJS.Platform,\n\tpowershell: boolean,\n): LinkTarget[] {\n\tconst targets: LinkTarget[] = [];\n\tfor (const name of ['npm', 'npx'] as const satisfies readonly ShimName[]) {\n\t\ttargets.push({ name, content: posixShim(home, name), mode: 0o755 });\n\t\tif (platform === 'win32') {\n\t\t\ttargets.push({ name: `${name}.cmd`, content: cmdShim(home, name), mode: 0o644 });\n\t\t\ttargets.push({\n\t\t\t\tname: `${name}.ps1`,\n\t\t\t\tcontent: powershell ? powershellShim(home, name) : null,\n\t\t\t\tmode: 0o644,\n\t\t\t});\n\t\t}\n\t}\n\treturn targets;\n}\n\nexport type LinkOutcome = 'linked' | 'already' | 'foreign' | 'unwritable' | 'missing';\n\nexport interface LinkResult {\n\ttarget: string;\n\toutcome: LinkOutcome;\n\tdetail?: string;\n}\n\n/** Keeps a copy of the original beside the target; a symlink is copied as a symlink. */\nfunction preserveOriginal(path: string, originalPath: string, meta: Meta): void {\n\tif (meta.type === 'symlink') {\n\t\tsymlinkSync(readlinkSync(path), originalPath);\n\t} else {\n\t\tcopyFileSync(path, originalPath);\n\t}\n}\n\n/** Puts the preserved original back in place of whatever is (or is not) at the target. */\nfunction restoreOriginal(dirs: Dirs, owner: OwnerRecord, entry: LinkRecord): void {\n\tconst originalPath = entry.originalPath as string;\n\tif (entry.original.type === 'symlink') {\n\t\tmutateFile(dirs.journal, 'link', owner, entry.target, null);\n\t\twithSharingRetry(() => renameSync(originalPath, entry.target));\n\t\treturn;\n\t}\n\tmutateFile(\n\t\tdirs.journal,\n\t\t'link',\n\t\towner,\n\t\tentry.target,\n\t\treadFileSync(originalPath),\n\t\tentry.original.mode || 0o755,\n\t);\n\trmSync(originalPath, { force: true });\n}\n\n/**\n * Replaces one entry point with a shim (spec LNK-2, LNK-3). The original is copied beside the target and\n * recorded before the journaled write, so a crash at any step leaves either a restorable original or the shim.\n * A file matching neither our shim nor the recorded original is reported and left alone.\n */\nexport function linkOne(\n\tdirs: Dirs,\n\towner: OwnerRecord,\n\tbinDir: string,\n\ttarget: LinkTarget,\n): LinkResult {\n\tconst path = join(binDir, target.name);\n\tconst originalPath = `${path}${ORIGINAL_SUFFIX}`;\n\tconst known = readLinks(dirs).entries.find((entry) => entry.target === path);\n\tlet current = captureMeta(path);\n\tif (\n\t\tcurrent.type === 'missing' &&\n\t\tknown !== undefined &&\n\t\tknown.shim.type !== 'missing' &&\n\t\tknown.originalPath !== null &&\n\t\texistsSync(known.originalPath)\n\t) {\n\t\t// A crash between moving the original aside and writing the shim: put the original back first.\n\t\trestoreOriginal(dirs, owner, known);\n\t\tforget(dirs, known);\n\t\tcurrent = captureMeta(path);\n\t}\n\tif (target.content === null) {\n\t\treturn moveAside(dirs, owner, binDir, target.name, known);\n\t}\n\tif (\n\t\tcurrent.type === 'missing' &&\n\t\tknown !== undefined &&\n\t\tknown.shim.type === 'missing' &&\n\t\tknown.originalPath !== null &&\n\t\tmetaMatches(known.originalPath, known.original)\n\t) {\n\t\t// Moved aside under a restrictive policy that is permissive again: the shim goes in, the original stays aside.\n\t\tmutateFile(dirs.journal, 'link', owner, path, Buffer.from(target.content, 'utf8'), target.mode);\n\t\trecord(dirs, { ...known, shim: captureMeta(path), linkedAt: new Date().toISOString() });\n\t\treturn { target: path, outcome: 'linked' };\n\t}\n\tif (current.type === 'missing') {\n\t\treturn { target: path, outcome: 'missing' };\n\t}\n\tif (current.type === 'file' && readFileSync(path, 'utf8') === target.content) {\n\t\tif (known === undefined) {\n\t\t\trecord(dirs, {\n\t\t\t\tbinDir,\n\t\t\t\tname: target.name,\n\t\t\t\ttarget: path,\n\t\t\t\toriginalPath: existsSync(originalPath) ? originalPath : null,\n\t\t\t\toriginal: captureMeta(originalPath),\n\t\t\t\tshim: current,\n\t\t\t\tlinkedAt: new Date().toISOString(),\n\t\t\t});\n\t\t} else if (known.shim.type === 'missing') {\n\t\t\t// A crash between writing the shim and recording it: the file is ours, the record catches up.\n\t\t\trecord(dirs, { ...known, shim: current, linkedAt: new Date().toISOString() });\n\t\t}\n\t\treturn { target: path, outcome: 'already' };\n\t}\n\tif (known !== undefined && metaMatches(path, known.shim)) {\n\t\t// Still our shim, only the template changed: rewrite it in place and keep the original where it is.\n\t\tmutateFile(dirs.journal, 'link', owner, path, Buffer.from(target.content, 'utf8'), target.mode);\n\t\trecord(dirs, { ...known, shim: captureMeta(path), linkedAt: new Date().toISOString() });\n\t\treturn { target: path, outcome: 'linked' };\n\t}\n\tif (known !== undefined && !metaMatches(path, known.original)) {\n\t\treturn { target: path, outcome: 'foreign', detail: 'changed since npm-vm linked it' };\n\t}\n\tif (existsSync(originalPath) && !metaMatches(originalPath, current)) {\n\t\treturn { target: path, outcome: 'foreign', detail: `${originalPath} already exists` };\n\t}\n\ttry {\n\t\tif (!existsSync(originalPath)) {\n\t\t\tpreserveOriginal(path, originalPath, current);\n\t\t}\n\t} catch (error) {\n\t\treturn { target: path, outcome: 'unwritable', detail: (error as Error).message };\n\t}\n\tconst entry: LinkRecord = {\n\t\tbinDir,\n\t\tname: target.name,\n\t\ttarget: path,\n\t\toriginalPath,\n\t\toriginal: current,\n\t\tshim: MISSING,\n\t\tlinkedAt: new Date().toISOString(),\n\t};\n\trecord(dirs, entry);\n\ttry {\n\t\tmutateFile(dirs.journal, 'link', owner, path, Buffer.from(target.content, 'utf8'), target.mode);\n\t} catch (error) {\n\t\treturn { target: path, outcome: 'unwritable', detail: (error as Error).message };\n\t}\n\trecord(dirs, { ...entry, shim: captureMeta(path) });\n\treturn { target: path, outcome: 'linked' };\n}\n\n/** Moves a file aside without a replacement, for Node's `.ps1` entry points when scripts are blocked. */\nfunction moveAside(\n\tdirs: Dirs,\n\towner: OwnerRecord,\n\tbinDir: string,\n\tname: string,\n\tknown: LinkRecord | undefined,\n): LinkResult {\n\tconst path = join(binDir, name);\n\tconst originalPath = `${path}${ORIGINAL_SUFFIX}`;\n\tconst current = captureMeta(path);\n\tif (known !== undefined && known.shim.type !== 'missing' && metaMatches(path, known.shim)) {\n\t\t// The policy turned restrictive after a link: drop our shim and keep the preserved original aside.\n\t\tmutateFile(dirs.journal, 'link', owner, path, null);\n\t\trecord(dirs, { ...known, shim: MISSING, linkedAt: new Date().toISOString() });\n\t\treturn { target: path, outcome: 'linked' };\n\t}\n\tif (current.type === 'missing') {\n\t\tif (known === undefined && existsSync(originalPath)) {\n\t\t\t// A crash after the rename and before the record: adopt the aside copy so unlink can restore it.\n\t\t\trecord(dirs, {\n\t\t\t\tbinDir,\n\t\t\t\tname,\n\t\t\t\ttarget: path,\n\t\t\t\toriginalPath,\n\t\t\t\toriginal: captureMeta(originalPath),\n\t\t\t\tshim: MISSING,\n\t\t\t\tlinkedAt: new Date().toISOString(),\n\t\t\t});\n\t\t\treturn { target: path, outcome: 'already' };\n\t\t}\n\t\treturn {\n\t\t\ttarget: path,\n\t\t\toutcome: known !== undefined && existsSync(originalPath) ? 'already' : 'missing',\n\t\t};\n\t}\n\tif (known !== undefined && !metaMatches(path, known.original)) {\n\t\treturn { target: path, outcome: 'foreign', detail: 'changed since npm-vm linked it' };\n\t}\n\tif (existsSync(originalPath) && !metaMatches(originalPath, current)) {\n\t\treturn { target: path, outcome: 'foreign', detail: `${originalPath} already exists` };\n\t}\n\ttry {\n\t\twithSharingRetry(() => renameSync(path, originalPath));\n\t} catch (error) {\n\t\treturn { target: path, outcome: 'unwritable', detail: (error as Error).message };\n\t}\n\trecord(dirs, {\n\t\tbinDir,\n\t\tname,\n\t\ttarget: path,\n\t\toriginalPath,\n\t\toriginal: current,\n\t\tshim: MISSING,\n\t\tlinkedAt: new Date().toISOString(),\n\t});\n\tvoid owner;\n\treturn { target: path, outcome: 'linked' };\n}\n\nexport type UnlinkOutcome = 'restored' | 'changed' | 'missing';\n\n/** Puts the original back only when the shim is still ours (spec MUT-5); a replaced file is left as is. */\nexport function unlinkOne(dirs: Dirs, owner: OwnerRecord, entry: LinkRecord): UnlinkOutcome {\n\tconst current = captureMeta(entry.target);\n\tconst hasOriginal = entry.originalPath !== null && existsSync(entry.originalPath);\n\tif (current.type === 'missing') {\n\t\tif (hasOriginal && metaMatches(entry.originalPath as string, entry.original)) {\n\t\t\trestoreOriginal(dirs, owner, entry);\n\t\t\tforget(dirs, entry);\n\t\t\treturn 'restored';\n\t\t}\n\t\tif (hasOriginal) {\n\t\t\treturn 'changed';\n\t\t}\n\t\tforget(dirs, entry);\n\t\treturn 'missing';\n\t}\n\tif (entry.shim.type === 'missing') {\n\t\t// The file was only moved aside; something else put a file back, which is not ours to replace.\n\t\treturn 'changed';\n\t}\n\tif (!metaMatches(entry.target, entry.shim)) {\n\t\treturn 'changed';\n\t}\n\tif (hasOriginal) {\n\t\trestoreOriginal(dirs, owner, entry);\n\t} else {\n\t\tmutateFile(dirs.journal, 'link', owner, entry.target, null);\n\t}\n\tforget(dirs, entry);\n\treturn 'restored';\n}\n\nfunction record(dirs: Dirs, entry: LinkRecord): void {\n\tconst links = readLinks(dirs);\n\tlinks.entries = [...links.entries.filter((item) => item.target !== entry.target), entry];\n\twriteLinks(dirs, links);\n}\n\nfunction forget(dirs: Dirs, entry: LinkRecord): void {\n\tconst links = readLinks(dirs);\n\tlinks.entries = links.entries.filter((item) => item.target !== entry.target);\n\twriteLinks(dirs, links);\n}\n\nexport function readLinks(dirs: Dirs): LinksFile {\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(join(dirs.state, LINKS_FILE), 'utf8')) as LinksFile;\n\t\treturn Array.isArray(parsed.entries) ? parsed : { version: 1, entries: [] };\n\t} catch {\n\t\treturn { version: 1, entries: [] };\n\t}\n}\n\nexport function writeLinks(dirs: Dirs, links: LinksFile): void {\n\tatomicWrite(join(dirs.state, LINKS_FILE), JSON.stringify(links, null, '\\t'), 0o600);\n}\n\n/** Whether a recorded link still holds our shim, for `doctor` (spec CLI). */\nexport function linkState(entry: LinkRecord): 'intact' | 'changed' | 'missing' {\n\tconst type = captureMeta(entry.target).type;\n\tif (entry.shim.type === 'missing') {\n\t\t// Moved aside on purpose (WIN-2): intact while nothing took its place and the preserved copy is still there.\n\t\tconst preserved =\n\t\t\tentry.originalPath !== null && metaMatches(entry.originalPath, entry.original);\n\t\treturn type === 'missing' ? (preserved ? 'intact' : 'missing') : 'changed';\n\t}\n\tif (type === 'missing') {\n\t\treturn 'missing';\n\t}\n\treturn metaMatches(entry.target, entry.shim) ? 'intact' : 'changed';\n}\n\nexport function describeInstall(install: NodeInstall): string {\n\treturn `${install.manager} ${install.version} (${install.binDir})`;\n}\n\nexport function isSymlinkTo(path: string, suffix: string): boolean {\n\ttry {\n\t\treturn lstatSync(path).isSymbolicLink() && basename(dirname(path)) === suffix;\n\t} catch {\n\t\treturn false;\n\t}\n}\n","import {\n\tcopyFileSync,\n\texistsSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trmSync,\n\tstatSync,\n\twriteFileSync,\n} from 'node:fs';\nimport { join } from 'node:path';\nimport { atomicRename, removeWithRetry } from '../state/atomic.ts';\n\nexport const BOOTSTRAP_FILE = 'bootstrap.cjs';\nexport const RUNTIME_FILE = 'runtime.cjs';\nexport const CURRENT_FILE = 'current';\nexport const PREVIOUS_FILE = 'previous';\nexport const MANIFEST_FILE = 'manifest.json';\nexport const VERSIONS_DIR = 'versions';\n\nexport interface VersionManifest {\n\tversion: string;\n\tabi: number;\n\tfiles: string[];\n}\n\n/**\n * Where this code's runtime build lives: beside an installed `runtime.cjs`, under `dist/runtime/` for the\n * bin, or `../../dist/runtime/` when running from source. Null when nothing has been built.\n */\nexport function runtimeDistDir(): string | null {\n\tconst here = import.meta.dirname;\n\tconst candidates = [\n\t\there,\n\t\tjoin(here, 'runtime'),\n\t\tjoin(here, '..', 'dist', 'runtime'),\n\t\tjoin(here, '..', '..', 'dist', 'runtime'),\n\t];\n\tfor (const candidate of candidates) {\n\t\tif (existsSync(join(candidate, RUNTIME_FILE)) && existsSync(join(candidate, BOOTSTRAP_FILE))) {\n\t\t\treturn candidate;\n\t\t}\n\t}\n\treturn null;\n}\n\nexport function versionDir(home: string, version: string): string {\n\treturn join(home, VERSIONS_DIR, version);\n}\n\nfunction copyTree(from: string, to: string, files: string[], prefix = ''): void {\n\tmkdirSync(to, { recursive: true, mode: 0o755 });\n\tfor (const name of readdirSync(from)) {\n\t\tconst source = join(from, name);\n\t\tconst target = join(to, name);\n\t\tif (statSync(source).isDirectory()) {\n\t\t\tcopyTree(source, target, files, `${prefix}${name}/`);\n\t\t} else {\n\t\t\tcopyFileSync(source, target);\n\t\t\tfiles.push(`${prefix}${name}`);\n\t\t}\n\t}\n}\n\n/**\n * Installs one runtime version under `versions/<version>/` atomically (spec SET-1): copied into a\n * temp dir beside it and renamed into place, so a crash never leaves a half-written version.\n */\nexport function installVersion(\n\thome: string,\n\tversion: string,\n\tdistDir: string,\n\tabi: number,\n): string {\n\tconst versions = join(home, VERSIONS_DIR);\n\tmkdirSync(versions, { recursive: true, mode: 0o755 });\n\tconst target = versionDir(home, version);\n\tconst staging = join(versions, `.${version}.${process.pid}.${Date.now()}`);\n\trmSync(staging, { recursive: true, force: true });\n\tconst files: string[] = [];\n\tcopyTree(distDir, staging, files);\n\tconst manifest: VersionManifest = { version, abi, files: files.toSorted() };\n\twriteFileSync(join(staging, MANIFEST_FILE), JSON.stringify(manifest, null, '\\t'));\n\t// The old copy moves aside and the new one moves in: two renames, no window where the version is deleted.\n\tconst replaced = join(versions, `.${version}.replaced.${process.pid}.${Date.now()}`);\n\tif (existsSync(target)) {\n\t\tatomicRename(target, replaced);\n\t}\n\ttry {\n\t\tatomicRename(staging, target);\n\t} catch (error) {\n\t\tif (existsSync(replaced)) {\n\t\t\tatomicRename(replaced, target);\n\t\t}\n\t\tthrow error;\n\t}\n\tremoveWithRetry(replaced);\n\treturn target;\n}\n\n/** Points `current` at an installed version; the write is atomic so a launcher never reads a partial file. */\nexport function setCurrent(home: string, version: string): void {\n\tconst temp = join(home, `.current.${process.pid}.${Date.now()}`);\n\twriteFileSync(temp, `${version}\\n`);\n\tatomicRename(temp, join(home, CURRENT_FILE));\n}\n\nexport function readCurrent(home: string): string | null {\n\ttry {\n\t\treturn readFileSync(join(home, CURRENT_FILE), 'utf8').trim();\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function readPrevious(home: string): string | null {\n\ttry {\n\t\treturn readFileSync(join(home, PREVIOUS_FILE), 'utf8').trim();\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Copies the launcher entry of an installed version to the home root, where the shims point. */\nexport function installBootstrap(home: string, version: string): void {\n\tconst source = join(versionDir(home, version), BOOTSTRAP_FILE);\n\tconst temp = join(home, `.${BOOTSTRAP_FILE}.${process.pid}.${Date.now()}`);\n\tcopyFileSync(source, temp);\n\tatomicRename(temp, join(home, BOOTSTRAP_FILE));\n}\n\nexport function readManifest(home: string, version: string): VersionManifest | null {\n\ttry {\n\t\treturn JSON.parse(\n\t\t\treadFileSync(join(versionDir(home, version), MANIFEST_FILE), 'utf8'),\n\t\t) as VersionManifest;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Removes copies a crashed reinstall moved aside; the launcher only reads them while `versions/<v>` is missing. */\nexport function sweepReplaced(home: string): void {\n\tlet names: string[];\n\ttry {\n\t\tnames = readdirSync(join(home, VERSIONS_DIR));\n\t} catch {\n\t\treturn;\n\t}\n\tfor (const name of names) {\n\t\tconst match = /^\\.(.+)\\.replaced\\./.exec(name);\n\t\tif (match !== null && existsSync(join(home, VERSIONS_DIR, match[1] as string, RUNTIME_FILE))) {\n\t\t\tremoveWithRetry(join(home, VERSIONS_DIR, name));\n\t\t}\n\t}\n}\n\nexport function installedVersions(home: string): string[] {\n\ttry {\n\t\treturn readdirSync(join(home, VERSIONS_DIR)).filter((name) => /^\\d+\\.\\d+\\.\\d+/.test(name));\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n/** The ABI an installed runtime declares, read from its manifest. */\nexport function runtimeAbi(home: string, version: string): number | null {\n\treturn readManifest(home, version)?.abi ?? null;\n}\n","import { execFileSync } from 'node:child_process';\nimport { accessSync, constants, existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { basename, dirname, join } from 'node:path';\nimport { atomicWrite } from '../state/atomic.ts';\nimport { mutateFile } from '../state/journal.ts';\nimport type { OwnerRecord } from '../state/lease.ts';\nimport { captureMeta, sha256 } from '../state/meta.ts';\nimport { powershellPath, shellBinary } from '../state/proc.ts';\nimport type { Dirs } from './home.ts';\nimport { BLOCK_END, BLOCK_START, profileBlock, type Shell } from './shell.ts';\n\nexport interface ProfileParts {\n\tpath: boolean;\n\thook: boolean;\n}\n\n/** One file `setup` would edit for one shell (spec SH-3). */\nexport interface ProfileTarget {\n\tshell: Shell;\n\tfile: string;\n\tparts: ProfileParts;\n}\n\nexport interface ProfileRecord {\n\tfile: string;\n\tshell: Shell;\n\tparts: ProfileParts;\n\t/** sha256 of the whole file as written, so `uninstall` can tell a later edit (spec MUT-5). */\n\twrittenSha256: string;\n\tbackup: string | null;\n\tupdatedAt: string;\n}\n\nexport interface ProfilesFile {\n\tversion: 1;\n\tentries: ProfileRecord[];\n}\n\nexport const PROFILES_FILE = 'profiles.json';\n\nconst BLOCK_RE = /^# >>> npm-vm >>>\\n[\\s\\S]*?^# <<< npm-vm <<<\\n?/m;\n\nfunction bashLoginFile(home: string): string {\n\tfor (const name of ['.bash_profile', '.bash_login', '.profile']) {\n\t\tif (existsSync(join(home, name))) {\n\t\t\treturn join(home, name);\n\t\t}\n\t}\n\treturn join(home, '.bash_profile');\n}\n\n/** The user profile of one PowerShell host, asked with `-NoProfile` so nothing of the user's runs (spec SEC-8). */\nexport function powershellProfile(\n\thost: 'powershell' | 'pwsh',\n\tenv: NodeJS.ProcessEnv,\n\tplatform: NodeJS.Platform = process.platform,\n): string | null {\n\tconst bin =\n\t\thost === 'powershell' ? powershellPath(env) : shellBinary('powershell', env, platform);\n\tif (bin === null) {\n\t\treturn null;\n\t}\n\ttry {\n\t\tconst out = execFileSync(\n\t\t\tbin,\n\t\t\t['-NoProfile', '-NonInteractive', '-Command', '$PROFILE.CurrentUserAllHosts'],\n\t\t\t{\n\t\t\t\tencoding: 'utf8',\n\t\t\t\tenv,\n\t\t\t\twindowsHide: true,\n\t\t\t\tstdio: ['ignore', 'pipe', 'ignore'],\n\t\t\t},\n\t\t).trim();\n\t\treturn out === '' ? null : out;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** The files to edit for `shells` (spec SH-3); PowerShell hosts that are not installed yield nothing. */\nexport function profileTargets(\n\tshells: readonly Shell[],\n\tenv: NodeJS.ProcessEnv = process.env,\n\tplatform: NodeJS.Platform = process.platform,\n\thome: string = env['HOME'] || homedir(),\n): ProfileTarget[] {\n\tconst targets: ProfileTarget[] = [];\n\tfor (const shell of shells) {\n\t\tswitch (shell) {\n\t\t\tcase 'zsh': {\n\t\t\t\tconst zdot = env['ZDOTDIR'] || home;\n\t\t\t\ttargets.push({ shell, file: join(zdot, '.zshenv'), parts: { path: true, hook: false } });\n\t\t\t\ttargets.push({ shell, file: join(zdot, '.zshrc'), parts: { path: false, hook: true } });\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'bash': {\n\t\t\t\ttargets.push({ shell, file: join(home, '.bashrc'), parts: { path: true, hook: true } });\n\t\t\t\tconst login = bashLoginFile(home);\n\t\t\t\tif (login !== join(home, '.bashrc')) {\n\t\t\t\t\ttargets.push({ shell, file: login, parts: { path: true, hook: false } });\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'fish': {\n\t\t\t\tconst config = env['XDG_CONFIG_HOME'] || join(home, '.config');\n\t\t\t\ttargets.push({\n\t\t\t\t\tshell,\n\t\t\t\t\tfile: join(config, 'fish', 'conf.d', 'npm-vm.fish'),\n\t\t\t\t\tparts: { path: true, hook: true },\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'powershell': {\n\t\t\t\tconst hosts: Array<'powershell' | 'pwsh'> =\n\t\t\t\t\tplatform === 'win32' ? ['powershell', 'pwsh'] : ['pwsh'];\n\t\t\t\tfor (const host of hosts) {\n\t\t\t\t\tconst file = powershellProfile(host, env, platform);\n\t\t\t\t\tif (file !== null && !targets.some((target) => target.file === file)) {\n\t\t\t\t\t\ttargets.push({ shell, file, parts: { path: true, hook: true } });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn targets;\n}\n\n/** Why a profile is printed instead of edited (spec SH-5), or null when editing it is fine. */\nexport function profileGuard(\n\tfile: string,\n\tenv: NodeJS.ProcessEnv = process.env,\n\tplatform: NodeJS.Platform = process.platform,\n): string | null {\n\tlet stat;\n\ttry {\n\t\tstat = lstatSync(file);\n\t} catch {\n\t\tstat = null;\n\t}\n\tif (stat !== null && stat.isSymbolicLink()) {\n\t\treturn 'it is a symlink, so a dotfile manager probably owns it';\n\t}\n\tlet probe = stat === null ? dirname(file) : file;\n\twhile (!existsSync(probe) && dirname(probe) !== probe) {\n\t\tprobe = dirname(probe);\n\t}\n\ttry {\n\t\taccessSync(probe, constants.W_OK);\n\t} catch {\n\t\treturn 'it is not writable';\n\t}\n\ttry {\n\t\tif (realpathSync(probe).startsWith('/nix/store')) {\n\t\t\treturn 'it lives in the Nix store (home-manager)';\n\t\t}\n\t} catch {\n\t\t// An unresolvable path is handled by the write itself.\n\t}\n\tconst chezmoi = join(env['HOME'] || homedir(), '.local', 'share', 'chezmoi');\n\tif (existsSync(join(chezmoi, `dot_${basename(file).replace(/^\\./, '')}`))) {\n\t\treturn 'chezmoi manages it';\n\t}\n\tif (platform === 'win32' && stat !== null && file.endsWith('.ps1')) {\n\t\tconst content = readFileSync(file, 'utf8');\n\t\tif (content.includes('# SIG # Begin signature block') && executionPolicy(env) === 'AllSigned') {\n\t\t\treturn 'it is signed and the execution policy is AllSigned';\n\t\t}\n\t}\n\treturn null;\n}\n\n/** The effective PowerShell execution policy, asked without a profile (spec WIN-2). */\nexport function executionPolicy(env: NodeJS.ProcessEnv = process.env): string | null {\n\ttry {\n\t\treturn execFileSync(\n\t\t\tpowershellPath(env),\n\t\t\t['-NoProfile', '-NonInteractive', '-Command', 'Get-ExecutionPolicy'],\n\t\t\t{\n\t\t\t\tencoding: 'utf8',\n\t\t\t\twindowsHide: true,\n\t\t\t\tstdio: ['ignore', 'pipe', 'ignore'],\n\t\t\t},\n\t\t).trim();\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport interface ProfileEdit {\n\ttarget: ProfileTarget;\n\tbefore: string | null;\n\tafter: string;\n\t/** A diff of the block the edit adds or replaces, for the consent prompt. */\n\tdiff: string;\n}\n\n/** The content with our block replaced or appended; a trailing newline is guaranteed before the block. */\nexport function withBlock(content: string | null, block: string): string {\n\tconst text = content ?? '';\n\tif (BLOCK_RE.test(text)) {\n\t\treturn text.replace(BLOCK_RE, block);\n\t}\n\tconst separator = text === '' || text.endsWith('\\n') ? '' : '\\n';\n\treturn `${text}${separator}${text === '' ? '' : '\\n'}${block}`;\n}\n\n/** The content without our block and the blank line that separated it; nothing else moves. */\nexport function withoutBlock(content: string): string {\n\tconst match = BLOCK_RE.exec(content);\n\tif (match === null) {\n\t\treturn content;\n\t}\n\tlet before = content.slice(0, match.index).replace(/\\n+$/, '\\n');\n\tif (before === '\\n') {\n\t\tbefore = '';\n\t}\n\tconst after = content.slice(match.index + match[0].length);\n\treturn before !== '' && after !== '' ? `${before}\\n${after}` : `${before}${after}`;\n}\n\nexport function currentBlock(content: string): string | null {\n\tconst match = BLOCK_RE.exec(content);\n\treturn match === null ? null : match[0];\n}\n\nfunction renderDiff(file: string, before: string | null, after: string): string {\n\tconst oldBlock = before === null ? null : currentBlock(before);\n\tconst newBlock = currentBlock(after) ?? '';\n\tconst lines = [`--- ${file}`, `+++ ${file}`];\n\tif (oldBlock !== null) {\n\t\tlines.push(\n\t\t\t...oldBlock\n\t\t\t\t.trimEnd()\n\t\t\t\t.split('\\n')\n\t\t\t\t.map((line) => `-${line}`),\n\t\t);\n\t}\n\tlines.push(\n\t\t...newBlock\n\t\t\t.trimEnd()\n\t\t\t.split('\\n')\n\t\t\t.map((line) => `+${line}`),\n\t);\n\treturn `${lines.join('\\n')}\\n`;\n}\n\n/** What `setup` would write for `target`, or null when the file already holds exactly this block. */\nexport function planProfileEdit(target: ProfileTarget, home: string): ProfileEdit | null {\n\tconst before = existsSync(target.file) ? readFileSync(target.file, 'utf8') : null;\n\tconst block = profileBlock(target.shell, home, target.parts);\n\tconst after = withBlock(before, block);\n\tif (before === after) {\n\t\treturn null;\n\t}\n\treturn { target, before, after, diff: renderDiff(target.file, before, after) };\n}\n\nfunction uniqueBackup(file: string): string {\n\tconst stamp = new Date().toISOString().replace(/[:.]/g, '-');\n\tlet candidate = `${file}.npm-vm-backup-${stamp}`;\n\tlet counter = 1;\n\twhile (existsSync(candidate)) {\n\t\tcandidate = `${file}.npm-vm-backup-${stamp}-${counter}`;\n\t\tcounter += 1;\n\t}\n\treturn candidate;\n}\n\n/** Applies one consented edit under a journal and a unique backup, and records it (spec SH-4). */\nexport function applyProfileEdit(dirs: Dirs, owner: OwnerRecord, edit: ProfileEdit): ProfileRecord {\n\tlet backup: string | null = null;\n\tif (edit.before !== null) {\n\t\tbackup = uniqueBackup(edit.target.file);\n\t\tatomicWrite(backup, edit.before, 0o600);\n\t}\n\tconst mode = edit.before === null ? 0o644 : captureMeta(edit.target.file).mode || 0o644;\n\tmutateFile(\n\t\tdirs.journal,\n\t\t'profile',\n\t\towner,\n\t\tedit.target.file,\n\t\tBuffer.from(edit.after, 'utf8'),\n\t\tmode,\n\t);\n\tconst record: ProfileRecord = {\n\t\tfile: edit.target.file,\n\t\tshell: edit.target.shell,\n\t\tparts: edit.target.parts,\n\t\twrittenSha256: sha256(edit.after),\n\t\tbackup,\n\t\tupdatedAt: new Date().toISOString(),\n\t};\n\tconst profiles = readProfiles(dirs);\n\tprofiles.entries = [...profiles.entries.filter((entry) => entry.file !== record.file), record];\n\twriteProfiles(dirs, profiles);\n\treturn record;\n}\n\nexport type RemoveOutcome = 'removed' | 'changed' | 'missing';\n\n/** Removes our block only when the file is still what we wrote (spec MUT-5); otherwise it is left alone. */\nexport function removeProfileBlock(\n\tdirs: Dirs,\n\towner: OwnerRecord,\n\trecord: ProfileRecord,\n): RemoveOutcome {\n\tif (!existsSync(record.file)) {\n\t\tforget(dirs, record);\n\t\treturn 'missing';\n\t}\n\tconst content = readFileSync(record.file, 'utf8');\n\tif (sha256(content) !== record.writtenSha256) {\n\t\treturn 'changed';\n\t}\n\tconst after = withoutBlock(content);\n\tmutateFile(\n\t\tdirs.journal,\n\t\t'profile',\n\t\towner,\n\t\trecord.file,\n\t\tafter.trim() === '' ? null : Buffer.from(after, 'utf8'),\n\t\tcaptureMeta(record.file).mode || 0o644,\n\t);\n\tforget(dirs, record);\n\treturn 'removed';\n}\n\nfunction forget(dirs: Dirs, record: ProfileRecord): void {\n\tconst profiles = readProfiles(dirs);\n\tprofiles.entries = profiles.entries.filter((entry) => entry.file !== record.file);\n\twriteProfiles(dirs, profiles);\n}\n\nexport function readProfiles(dirs: Dirs): ProfilesFile {\n\ttry {\n\t\tconst parsed = JSON.parse(\n\t\t\treadFileSync(join(dirs.state, PROFILES_FILE), 'utf8'),\n\t\t) as ProfilesFile;\n\t\treturn Array.isArray(parsed.entries) ? parsed : { version: 1, entries: [] };\n\t} catch {\n\t\treturn { version: 1, entries: [] };\n\t}\n}\n\nexport function writeProfiles(dirs: Dirs, profiles: ProfilesFile): void {\n\tatomicWrite(join(dirs.state, PROFILES_FILE), JSON.stringify(profiles, null, '\\t'), 0o600);\n}\n\nexport { BLOCK_END, BLOCK_START };\n","import { execFileSync } from 'node:child_process';\nimport { join } from 'node:path';\nimport { powershellPath } from '../state/proc.ts';\n\n/*\n * Windows integration (spec WIN-1 to WIN-3). Every helper runs by absolute path with no profile (SEC-8).\n * `[Environment]::SetEnvironmentVariable(..., 'User')` writes HKCU\\Environment and broadcasts WM_SETTINGCHANGE, so no setx.\n */\n\nfunction powershell(env: NodeJS.ProcessEnv, command: string): string {\n\treturn execFileSync(powershellPath(env), ['-NoProfile', '-NonInteractive', '-Command', command], {\n\t\tencoding: 'utf8',\n\t\tenv,\n\t\twindowsHide: true,\n\t\tstdio: ['ignore', 'pipe', 'pipe'],\n\t}).trim();\n}\n\nfunction regExe(env: NodeJS.ProcessEnv): string {\n\treturn join(env['SystemRoot'] ?? 'C:\\\\Windows', 'System32', 'reg.exe');\n}\n\nfunction quote(value: string): string {\n\treturn `'${value.replace(/'/g, \"''\")}'`;\n}\n\nexport function readUserPath(env: NodeJS.ProcessEnv): string {\n\treturn powershell(env, \"[Environment]::GetEnvironmentVariable('Path', 'User')\");\n}\n\nexport function writeUserPath(env: NodeJS.ProcessEnv, value: string): void {\n\tpowershell(env, `[Environment]::SetEnvironmentVariable('Path', ${quote(value)}, 'User')`);\n}\n\nfunction sameDir(a: string, b: string): boolean {\n\treturn a.replace(/[\\\\/]+$/, '').toLowerCase() === b.replace(/[\\\\/]+$/, '').toLowerCase();\n}\n\n/** Prepends `dir` to the user PATH unless present; returns whether anything changed. */\nexport function addToUserPath(env: NodeJS.ProcessEnv, dir: string): boolean {\n\tconst current = readUserPath(env);\n\tconst parts = current.split(';').filter((part) => part !== '');\n\tif (parts.some((part) => sameDir(part, dir))) {\n\t\treturn false;\n\t}\n\twriteUserPath(env, [dir, ...parts].join(';'));\n\treturn true;\n}\n\nexport function removeFromUserPath(env: NodeJS.ProcessEnv, dir: string): boolean {\n\tconst current = readUserPath(env);\n\tconst parts = current.split(';').filter((part) => part !== '');\n\tconst kept = parts.filter((part) => !sameDir(part, dir));\n\tif (kept.length === parts.length) {\n\t\treturn false;\n\t}\n\twriteUserPath(env, kept.join(';'));\n\treturn true;\n}\n\nconst AUTORUN_KEY = 'HKCU\\\\Software\\\\Microsoft\\\\Command Processor';\nconst AUTORUN_MARK = 'npm-vm';\n\nexport function readCmdAutoRun(env: NodeJS.ProcessEnv): string | null {\n\ttry {\n\t\tconst out = execFileSync(regExe(env), ['query', AUTORUN_KEY, '/v', 'AutoRun'], {\n\t\t\tencoding: 'utf8',\n\t\t\twindowsHide: true,\n\t\t\tstdio: ['ignore', 'pipe', 'ignore'],\n\t\t});\n\t\treturn /AutoRun\\s+REG_(?:EXPAND_)?SZ\\s+(.*)$/m.exec(out)?.[1]?.trim() ?? null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** The cmd AutoRun entry that puts shims first in every cmd session; only with `--cmd-autorun` (WIN-3). */\nexport function autoRunCommand(shimsDir: string): string {\n\treturn `set \"PATH=${shimsDir};%PATH%\" & rem ${AUTORUN_MARK}`;\n}\n\n/** `value` without the fragment `autoRunCommand` generated, whatever home it named; the user's own commands stay. */\nexport function withoutAutoRunCommand(value: string | null): string {\n\tif (value === null) {\n\t\treturn '';\n\t}\n\treturn value.replace(/^set \"PATH=[^\"]*;%PATH%\" & rem npm-vm(?: & )?/, '').trim();\n}\n\nexport function setCmdAutoRun(env: NodeJS.ProcessEnv, shimsDir: string): void {\n\tconst ours = autoRunCommand(shimsDir);\n\tconst kept = withoutAutoRunCommand(readCmdAutoRun(env));\n\tconst value = kept === '' ? ours : `${ours} & ${kept}`;\n\texecFileSync(\n\t\tregExe(env),\n\t\t['add', AUTORUN_KEY, '/v', 'AutoRun', '/t', 'REG_SZ', '/d', value, '/f'],\n\t\t{\n\t\t\twindowsHide: true,\n\t\t\tstdio: 'ignore',\n\t\t},\n\t);\n}\n\nexport function clearCmdAutoRun(env: NodeJS.ProcessEnv): boolean {\n\tconst existing = readCmdAutoRun(env);\n\tif (existing === null || !existing.includes(`rem ${AUTORUN_MARK}`)) {\n\t\treturn false;\n\t}\n\tconst rest = withoutAutoRunCommand(existing);\n\tif (rest === '') {\n\t\texecFileSync(regExe(env), ['delete', AUTORUN_KEY, '/v', 'AutoRun', '/f'], {\n\t\t\twindowsHide: true,\n\t\t\tstdio: 'ignore',\n\t\t});\n\t} else {\n\t\texecFileSync(\n\t\t\tregExe(env),\n\t\t\t['add', AUTORUN_KEY, '/v', 'AutoRun', '/t', 'REG_SZ', '/d', rest, '/f'],\n\t\t\t{\n\t\t\t\twindowsHide: true,\n\t\t\t\tstdio: 'ignore',\n\t\t\t},\n\t\t);\n\t}\n\treturn true;\n}\n\n/** Whether the effective execution policy lets our unsigned `.ps1` shims run (spec WIN-2). */\nexport function powershellAllowsScripts(policy: string | null): boolean {\n\treturn policy !== null && !['Restricted', 'AllSigned', 'Undefined'].includes(policy);\n}\n\n/** Which `npm` each Windows context resolves first, for `doctor`. */\nexport function windowsWinners(\n\tenv: NodeJS.ProcessEnv,\n): Array<{ context: string; path: string | null }> {\n\tconst results: Array<{ context: string; path: string | null }> = [];\n\ttry {\n\t\tconst out = execFileSync(\n\t\t\tjoin(env['SystemRoot'] ?? 'C:\\\\Windows', 'System32', 'where.exe'),\n\t\t\t['npm'],\n\t\t\t{\n\t\t\t\tencoding: 'utf8',\n\t\t\t\tenv,\n\t\t\t\twindowsHide: true,\n\t\t\t\tstdio: ['ignore', 'pipe', 'ignore'],\n\t\t\t},\n\t\t);\n\t\tresults.push({ context: 'cmd', path: out.split(/\\r?\\n/)[0] ?? null });\n\t} catch {\n\t\tresults.push({ context: 'cmd', path: null });\n\t}\n\ttry {\n\t\tresults.push({\n\t\t\tcontext: 'PowerShell',\n\t\t\tpath: powershell(env, '(Get-Command npm -All | Select-Object -First 1).Source') || null,\n\t\t});\n\t} catch {\n\t\tresults.push({ context: 'PowerShell', path: null });\n\t}\n\treturn results;\n}\n","import { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync, realpathSync } from 'node:fs';\nimport { basename, join } from 'node:path';\nimport { EXIT } from '../errors.ts';\nimport { findProject } from '../project.ts';\nimport { listJournals } from '../state/journal.ts';\nimport { lockOwnerLive, lockPath, readLock } from '../state/lock.ts';\nimport { shellBinary } from '../state/proc.ts';\nimport { findNodeInstalls, linkState, readLinks } from '../setup/link.ts';\nimport { BOOTSTRAP_FILE, readCurrent, readManifest, versionDir } from '../setup/layout.ts';\nimport { readProfiles } from '../setup/profile.ts';\nimport { BLOCK_START, isShell, type Shell } from '../setup/shell.ts';\nimport { SELECTORS, SHIM_ABI, shimAbi, shimDir } from '../setup/shims.ts';\nimport { windowsWinners } from '../setup/windows.ts';\nimport type { CommandContext } from './context.ts';\n\nexport interface Problem {\n\tcheck: string;\n\tdetail: string;\n\tfix: string;\n}\n\nexport interface DoctorReport {\n\thome: string;\n\tversion: string | null;\n\tproblems: Problem[];\n\tnotes: string[];\n}\n\nconst PROBE_TIMEOUT_MS = 5000;\n\n/** The `npm` an interactive login shell resolves, by asking that shell (its profiles decide the PATH). */\nfunction shellWinner(shell: Shell, env: NodeJS.ProcessEnv): string | null {\n\tconst bin = shellBinary(shell, env);\n\tif (bin === null) {\n\t\treturn null;\n\t}\n\t/* `-c` never reaches a prompt, so the hooks run by hand first: on macOS, /etc/zprofile reorders PATH after .zshenv. */\n\tconst args =\n\t\tshell === 'fish'\n\t\t\t? ['-l', '-i', '-c', 'emit fish_prompt; command -v npm']\n\t\t\t: shell === 'powershell'\n\t\t\t\t? ['-NoProfile', '-Command', '(Get-Command npm).Source']\n\t\t\t\t: shell === 'zsh'\n\t\t\t\t\t? ['-l', '-i', '-c', 'for f in $precmd_functions; do \"$f\"; done; command -v npm']\n\t\t\t\t\t: ['-l', '-i', '-c', 'eval \"$PROMPT_COMMAND\"; command -v npm'];\n\ttry {\n\t\tconst out = execFileSync(bin, args, {\n\t\t\tencoding: 'utf8',\n\t\t\tenv,\n\t\t\ttimeout: PROBE_TIMEOUT_MS,\n\t\t\tstdio: ['ignore', 'pipe', 'ignore'],\n\t\t})\n\t\t\t.trim()\n\t\t\t.split('\\n')\n\t\t\t.pop();\n\t\treturn out === undefined || out === '' ? null : out;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** A Windows path for comparison: `where` answers with the long name, the home may carry an 8.3 short name. */\nfunction canonical(path: string): string {\n\ttry {\n\t\treturn realpathSync.native(path).toLowerCase();\n\t} catch {\n\t\treturn path.toLowerCase();\n\t}\n}\n\n/** What `command -v npm` printed: an alias or a function wins over PATH, so no PATH fix can help. */\nexport function winnerKind(winner: string): 'alias' | 'function' | 'path' {\n\tif (winner.startsWith('alias ')) {\n\t\treturn 'alias';\n\t}\n\treturn winner === 'npm' ? 'function' : 'path';\n}\n\nfunction samePath(a: string, b: string, platform: NodeJS.Platform): boolean {\n\treturn platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;\n}\n\nexport async function collect(context: CommandContext): Promise<DoctorReport> {\n\tconst { dirs, env, platform } = context;\n\tconst report: DoctorReport = {\n\t\thome: dirs.home,\n\t\tversion: readCurrent(dirs.home),\n\t\tproblems: [],\n\t\tnotes: [],\n\t};\n\tconst setupHint = 'Run `npx --prefix ~ -y @mawesome/npm-vm setup`.';\n\tconst problem = (check: string, detail: string, fix: string): void => {\n\t\treport.problems.push({ check, detail, fix });\n\t};\n\n\tif (report.version === null || readManifest(dirs.home, report.version) === null) {\n\t\tproblem('runtime', `no runtime is installed under ${dirs.home}`, setupHint);\n\t} else {\n\t\tconst root = join(dirs.home, BOOTSTRAP_FILE);\n\t\tconst shipped = join(versionDir(dirs.home, report.version), BOOTSTRAP_FILE);\n\t\tif (!existsSync(root) || !readFileSync(root).equals(readFileSync(shipped))) {\n\t\t\tproblem('launcher', `${root} differs from the installed version's launcher`, setupHint);\n\t\t}\n\t}\n\tfor (const name of SELECTORS) {\n\t\tconst file = join(shimDir(dirs.home), name);\n\t\tconst abi = existsSync(file) ? shimAbi(readFileSync(file, 'utf8')) : null;\n\t\tif (abi === null) {\n\t\t\tproblem('shims', `${file} is missing or not an npm-vm shim`, setupHint);\n\t\t} else if (abi !== SHIM_ABI) {\n\t\t\tproblem(\n\t\t\t\t'shims',\n\t\t\t\t`${file} declares launcher ABI ${abi}, this version needs ${SHIM_ABI}`,\n\t\t\t\tsetupHint,\n\t\t\t);\n\t\t}\n\t}\n\tif (dirs.machine.fallback) {\n\t\treport.notes.push(\n\t\t\t'The machine id falls back to the hostname; cloned machines or containers sharing this home could collide in the cache.',\n\t\t);\n\t}\n\tconst lock = readLock(dirs.state);\n\tif (lock !== null && !lockOwnerLive(lock, dirs.machine.id)) {\n\t\tproblem(\n\t\t\t'lock',\n\t\t\t`${lockPath(dirs.state)} is held by PID ${lock.pid}, which no longer runs`,\n\t\t\t`Delete ${lockPath(dirs.state)}.`,\n\t\t);\n\t}\n\tfor (const journal of listJournals(dirs.journal)) {\n\t\tconst foreign = journal.owner.machineId !== dirs.machine.id;\n\t\tproblem(\n\t\t\t'journal',\n\t\t\t`${journal.id} (${journal.kind}) for ${journal.target} was left by ${foreign ? `another machine (${journal.owner.host})` : `PID ${journal.owner.pid}`}`,\n\t\t\tforeign\n\t\t\t\t? `Confirm no npm-vm runs on ${journal.owner.host}, then run \\`npm-vm recover --journal ${journal.id} --confirm-dead-machine ${journal.owner.machineId}\\`.`\n\t\t\t\t: 'Run any npm-vm command; dead owners are recovered automatically.',\n\t\t);\n\t}\n\n\tconst profiles = readProfiles(dirs);\n\tfor (const entry of profiles.entries) {\n\t\tif (!existsSync(entry.file) || !readFileSync(entry.file, 'utf8').includes(BLOCK_START)) {\n\t\t\tproblem(\n\t\t\t\t'profile',\n\t\t\t\t`${entry.file} no longer holds the npm-vm block`,\n\t\t\t\t`Run \\`npm-vm init ${entry.shell}\\` and add the block, or run setup again.`,\n\t\t\t);\n\t\t}\n\t}\n\tconst shimsDir = shimDir(dirs.home);\n\tif (platform === 'win32') {\n\t\tconst shimsCanonical = canonical(shimsDir);\n\t\tfor (const winner of windowsWinners(env)) {\n\t\t\tif (winner.path === null || !canonical(winner.path).startsWith(shimsCanonical)) {\n\t\t\t\tproblem(\n\t\t\t\t\t'path',\n\t\t\t\t\t`${winner.context} resolves npm to ${winner.path ?? 'nothing'}`,\n\t\t\t\t\t'Run setup again, then restart the terminal (M-RESTART).',\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t} else {\n\t\tconst login = basename(env['SHELL'] ?? '');\n\t\tconst shells = new Set<Shell>([\n\t\t\t...profiles.entries.map((entry) => entry.shell),\n\t\t\t...(isShell(login) ? [login] : []),\n\t\t]);\n\t\tfor (const shell of shells) {\n\t\t\tif (shell === 'powershell') {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst winner = shellWinner(shell, env);\n\t\t\tif (winner === null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst kind = winnerKind(winner);\n\t\t\tif (kind !== 'path') {\n\t\t\t\tproblem(\n\t\t\t\t\t'path',\n\t\t\t\t\t`${shell} resolves npm to a shell ${kind}: ${winner}`,\n\t\t\t\t\t`A shell ${kind} wins over PATH. Remove it from your ${shell} profile, or make it run ${join(shimsDir, 'npm')}.`,\n\t\t\t\t);\n\t\t\t} else if (!samePath(winner, join(shimsDir, 'npm'), platform)) {\n\t\t\t\tconst corepack = winner.includes('corepack') ? ' (a Corepack shim)' : '';\n\t\t\t\tproblem(\n\t\t\t\t\t'path',\n\t\t\t\t\t`${shell} resolves npm to ${winner}${corepack}`,\n\t\t\t\t\t`Add the snippet from \\`npm-vm init ${shell}\\` after your Node manager's init line, or run setup with --link.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst links = readLinks(dirs);\n\tif (links.entries.length > 0) {\n\t\tfor (const entry of links.entries) {\n\t\t\tconst state = linkState(entry);\n\t\t\tif (state !== 'intact') {\n\t\t\t\tproblem(\n\t\t\t\t\t'link',\n\t\t\t\t\t`${entry.target} is ${state === 'missing' ? 'missing' : 'no longer the npm-vm shim'}`,\n\t\t\t\t\t'Run `npm-vm setup --link` to relink, or `npm-vm uninstall` to stop linking.',\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tconst linked = new Set(links.entries.map((entry) => entry.binDir));\n\t\tfor (const install of findNodeInstalls(env, platform)) {\n\t\t\tif (!linked.has(install.binDir)) {\n\t\t\t\tproblem(\n\t\t\t\t\t'link',\n\t\t\t\t\t`${install.manager} ${install.version} at ${install.binDir} is not linked`,\n\t\t\t\t\t'Run `npm-vm setup --link`.',\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\treport.notes.push(\n\t\t...findNodeInstalls(env, platform).map(\n\t\t\t(install) => `Found ${install.manager} ${install.version} at ${install.binDir}`,\n\t\t),\n\t);\n\n\tconst project = findProject([], process.cwd(), env);\n\tif (existsSync(join(project.root, 'node_modules', '.bin', 'npm'))) {\n\t\treport.notes.push(\n\t\t\t`${project.root}/node_modules/.bin/npm exists; npm scripts in this project run it instead of the shim.`,\n\t\t);\n\t}\n\treturn report;\n}\n\nexport async function doctor(\n\tcontext: CommandContext,\n\toptions: { quiet?: boolean } = {},\n): Promise<number> {\n\tconst report = await collect(context);\n\tif (options.quiet) {\n\t\treturn report.problems.length === 0 ? EXIT.ok : EXIT.problems;\n\t}\n\tif (context.json) {\n\t\tcontext.io.out(JSON.stringify(report, null, 2));\n\t} else {\n\t\tconst lines = [`npm-vm ${report.version ?? '(not installed)'} in ${report.home}`];\n\t\tfor (const problem of report.problems) {\n\t\t\tlines.push(` problem [${problem.check}]: ${problem.detail}`, ` fix: ${problem.fix}`);\n\t\t}\n\t\tfor (const note of report.notes) {\n\t\t\tlines.push(` note: ${note}`);\n\t\t}\n\t\tlines.push(\n\t\t\treport.problems.length === 0 ? ' healthy' : ` ${report.problems.length} problem(s)`,\n\t\t);\n\t\tcontext.io.out(lines.join('\\n'));\n\t}\n\treturn report.problems.length === 0 ? EXIT.ok : EXIT.problems;\n}\n","import { existsSync, readFileSync, statSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport semver from 'semver';\nimport { EXIT, NpmVmError } from '../errors.ts';\nimport { createContext, createInstaller } from '../install/index.ts';\nimport { findProject } from '../project.ts';\nimport { parseVersionSpec } from '../spec.ts';\nimport { mutateFile, recoverDeadJournals } from '../state/journal.ts';\nimport { acquireLock } from '../state/lock.ts';\nimport type { CommandContext } from './context.ts';\n\n/** The indentation and newline a JSON file uses, so the rewrite keeps its shape. */\nexport function detectFormat(text: string): {\n\tindent: string;\n\tnewline: '\\n' | '\\r\\n';\n\ttrailingNewline: boolean;\n} {\n\tconst indent = /^[ \\t]+(?=\")/m.exec(text)?.[0] ?? ' ';\n\treturn {\n\t\tindent,\n\t\tnewline: text.includes('\\r\\n') ? '\\r\\n' : '\\n',\n\t\ttrailingNewline: text.endsWith('\\n'),\n\t};\n}\n\n/** `devEngines.packageManager` with one npm entry, keeping other managers and the field's shape. */\nexport function pinnedManifest(\n\tpkg: Record<string, unknown>,\n\tversion: string,\n): Record<string, unknown> {\n\tconst entry = { name: 'npm', version, onFail: 'error' };\n\tconst devEngines =\n\t\ttypeof pkg['devEngines'] === 'object' && pkg['devEngines'] !== null\n\t\t\t? { ...(pkg['devEngines'] as Record<string, unknown>) }\n\t\t\t: {};\n\tconst existing = devEngines['packageManager'];\n\tif (Array.isArray(existing)) {\n\t\tconst others = existing.filter(\n\t\t\t(item) =>\n\t\t\t\t!(typeof item === 'object' && item !== null && (item as { name?: unknown }).name === 'npm'),\n\t\t);\n\t\tdevEngines['packageManager'] = [...others, entry];\n\t} else if (\n\t\ttypeof existing === 'object' &&\n\t\texisting !== null &&\n\t\t(existing as { name?: unknown }).name !== 'npm'\n\t) {\n\t\tdevEngines['packageManager'] = [existing, entry];\n\t} else {\n\t\tdevEngines['packageManager'] = entry;\n\t}\n\treturn { ...pkg, devEngines };\n}\n\nfunction nearestManifestDir(cwd: string): string | null {\n\tlet dir = cwd;\n\tfor (;;) {\n\t\tif (existsSync(join(dir, 'package.json'))) {\n\t\t\treturn dir;\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) {\n\t\t\treturn null;\n\t\t}\n\t\tdir = parent;\n\t}\n}\n\n/** `^<latest npm whose engines accept the active Node>`, asked from the registry. */\nasync function defaultRange(context: CommandContext): Promise<string> {\n\tconst installer = createInstaller(createContext(context.env, context.dirs.home));\n\tconst candidates = await installer.registry([parseVersionSpec('>=8', 'pin')]);\n\tconst usable = candidates.filter(\n\t\t(candidate) =>\n\t\t\tcandidate.enginesNode === null ||\n\t\t\tsemver.satisfies(process.version, candidate.enginesNode, { includePrerelease: true }),\n\t);\n\tconst latest = usable.map((candidate) => candidate.version).toSorted(semver.rcompare)[0];\n\tif (latest === undefined) {\n\t\tthrow new NpmVmError(\n\t\t\t'M-NOMATCH',\n\t\t\tEXIT.resolution,\n\t\t\t`No npm release supports Node ${process.version}.`,\n\t\t);\n\t}\n\treturn `^${latest}`;\n}\n\nexport async function pin(\n\tcontext: CommandContext,\n\trange: string | undefined,\n\tcwd: string = process.cwd(),\n): Promise<number> {\n\tconst project = findProject([], cwd, context.env);\n\tconst nearest = nearestManifestDir(cwd);\n\tif (nearest !== null && nearest !== project.root) {\n\t\tthrow new NpmVmError(\n\t\t\t'M-NOMATCH',\n\t\t\tEXIT.usage,\n\t\t\t`${nearest} is a workspace of ${project.root}; npm reads devEngines from the root. Run pin from ${project.root} to pin it there.`,\n\t\t);\n\t}\n\tconst file = join(project.root, 'package.json');\n\tif (!existsSync(file)) {\n\t\tthrow new NpmVmError('M-NOMATCH', EXIT.usage, `No package.json in ${project.root}.`);\n\t}\n\tconst version = range ?? (await defaultRange(context));\n\ttry {\n\t\tparseVersionSpec(version, 'pin');\n\t} catch (error) {\n\t\tthrow new NpmVmError('M-NOMATCH', EXIT.usage, (error as Error).message);\n\t}\n\t// The manifest is read and rewritten under the exclusive lock (spec MUT-1), like every other mutation.\n\tconst lock = await acquireLock(context.dirs.state, context.owner);\n\ttry {\n\t\trecoverDeadJournals(context.dirs.journal, context.dirs.machine.id);\n\t\tconst text = readFileSync(file, 'utf8');\n\t\tlet pkg: Record<string, unknown>;\n\t\ttry {\n\t\t\tpkg = JSON.parse(text) as Record<string, unknown>;\n\t\t} catch (error) {\n\t\t\tthrow new NpmVmError(\n\t\t\t\t'M-NOMATCH',\n\t\t\t\tEXIT.usage,\n\t\t\t\t`${file} is not valid JSON: ${(error as Error).message}`,\n\t\t\t);\n\t\t}\n\t\tconst format = detectFormat(text);\n\t\tconst body = JSON.stringify(pinnedManifest(pkg, version), null, format.indent).replace(\n\t\t\t/\\n/g,\n\t\t\tformat.newline,\n\t\t);\n\t\tconst output = `${body}${format.trailingNewline ? format.newline : ''}`;\n\t\tif (output !== text) {\n\t\t\tconst mode = process.platform === 'win32' ? 0o644 : statSync(file).mode & 0o7777;\n\t\t\tmutateFile(\n\t\t\t\tcontext.dirs.journal,\n\t\t\t\t'project',\n\t\t\t\tcontext.owner,\n\t\t\t\tfile,\n\t\t\t\tBuffer.from(output, 'utf8'),\n\t\t\t\tmode,\n\t\t\t);\n\t\t}\n\t} finally {\n\t\tlock.release();\n\t}\n\tcontext.io.out(\n\t\tcontext.json ? JSON.stringify({ file, version }) : `Pinned npm ${version} in ${file}`,\n\t);\n\treturn EXIT.ok;\n}\n","import { execFile } from 'node:child_process';\nimport { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { Agent, ProxyAgent, request, type Dispatcher } from 'undici';\nimport { EXIT, NpmVmError } from '../errors.ts';\nimport { provenanceMessage, redactUrls } from '../messages.ts';\nimport type { NpmConfigView } from './config.ts';\n\n/** What the attestation must say about this repository's release workflow (spec SUP-2). */\nexport const PROVENANCE_ISSUER = 'https://token.actions.githubusercontent.com';\nexport const PROVENANCE_IDENTITY =\n\t'https://github.com/mawesomedev/mawesome/.github/workflows/release.yml@refs/heads/main';\nexport const SLSA_PREDICATE = 'https://slsa.dev/provenance/v1';\n\nexport interface ProvenanceInput {\n\tname: string;\n\tversion: string;\n\t/** Hex sha512 of the tarball being installed. */\n\tsha512hex: string;\n\t/** `dist.attestations.url` from the packument; only its path is used (SUP-2). */\n\tattestationsUrl: string | null;\n\tconfig: NpmConfigView;\n\tstateDir: string;\n}\n\nexport interface Attestation {\n\tpredicateType: string;\n\tbundle: unknown;\n}\n\nexport type AttestationFetcher = (url: URL, config: NpmConfigView) => Promise<Attestation[]>;\nexport type BundleVerifier = (\n\tbundle: unknown,\n\toptions: { tufCachePath: string; config: NpmConfigView; env: NodeJS.ProcessEnv },\n) => Promise<void>;\n\nfunction failure(name: string, version: string, detail: string): NpmVmError {\n\treturn new NpmVmError(\n\t\t'M-PROVENANCE',\n\t\tEXIT.verification,\n\t\tprovenanceMessage(name, version, detail),\n\t);\n}\n\n/** Resolves the attestation path against the configured registry: never another origin (spec SUP-2). */\nexport function attestationUrl(\n\tinput: Pick<ProvenanceInput, 'name' | 'version' | 'attestationsUrl'>,\n\tregistry: string,\n): URL {\n\tconst base = new URL(registry);\n\tconst url = new URL(base);\n\tif (input.attestationsUrl !== null) {\n\t\t// Assigned, not re-parsed: a pathname starting with `//host` would otherwise become another origin.\n\t\tconst given = new URL(input.attestationsUrl, base);\n\t\turl.pathname = given.pathname;\n\t\turl.search = given.search;\n\t} else {\n\t\turl.pathname = `${base.pathname.replace(/\\/$/, '')}/-/npm/v1/attestations/${encodeURIComponent(input.name)}@${input.version}`;\n\t\turl.search = '';\n\t}\n\turl.hash = '';\n\t// Credentials travel in the Authorization header, never inline in the URL.\n\turl.username = '';\n\turl.password = '';\n\tif (url.origin !== base.origin) {\n\t\tthrow new Error(\n\t\t\t`attestation URL ${redactUrls(url.href)} leaves the registry origin ${base.origin}`,\n\t\t);\n\t}\n\treturn url;\n}\n\n/** TLS settings npm itself would use: `ca` and `cafile`, `strict-ssl`, and the registry's client certificate (spec DL-2). */\nexport function tlsOptions(config: NpmConfigView): {\n\trejectUnauthorized: boolean;\n\tca?: string[];\n\tcert?: string;\n\tkey?: string;\n} {\n\tconst ca = [...(config.ca ?? [])];\n\tif (config.cafile !== null) {\n\t\tca.push(readFileSync(config.cafile, 'utf8'));\n\t}\n\tconst { certfile, keyfile } = config.credentials;\n\treturn {\n\t\trejectUnauthorized: config.strictSsl,\n\t\t...(ca.length === 0 ? {} : { ca }),\n\t\t...(certfile !== undefined && keyfile !== undefined\n\t\t\t? { cert: readFileSync(certfile, 'utf8'), key: readFileSync(keyfile, 'utf8') }\n\t\t\t: {}),\n\t};\n}\n\n/** `noproxy` the way @npmcli/agent reads it: comma or space separated, `*` for all, `host[:port]`, leading dots and `*.`. */\nexport function noProxyMatches(noproxy: string | null, url: URL): boolean {\n\tconst port = url.port || (url.protocol === 'https:' ? '443' : '80');\n\treturn (noproxy ?? '')\n\t\t.split(/[\\s,]+/)\n\t\t.map((item) => item.trim().toLowerCase())\n\t\t.filter((item) => item !== '')\n\t\t.some((item) => {\n\t\t\tif (item === '*') {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tconst [host, itemPort] = item.split(':') as [string, string | undefined];\n\t\t\tif (itemPort !== undefined && itemPort !== port) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tconst bare = host.replace(/^\\*?\\./, '');\n\t\t\treturn url.hostname === bare || url.hostname.endsWith(`.${bare}`);\n\t\t});\n}\n\nfunction dispatcherFor(config: NpmConfigView, url: URL): Dispatcher {\n\tconst proxy = url.protocol === 'https:' ? (config.httpsProxy ?? config.proxy) : config.proxy;\n\tconst bypass = noProxyMatches(config.noproxy, url);\n\tconst tls = tlsOptions(config);\n\tif (proxy !== null && !bypass) {\n\t\treturn new ProxyAgent({ uri: proxy, requestTls: tls });\n\t}\n\treturn new Agent({ connect: tls });\n}\n\nfunction authHeader(config: NpmConfigView): Record<string, string> {\n\tconst { token, username, password, auth } = config.credentials;\n\tif (token !== undefined) {\n\t\treturn { authorization: `Bearer ${token}` };\n\t}\n\tif (auth !== undefined) {\n\t\treturn { authorization: `Basic ${auth}` };\n\t}\n\tif (username !== undefined && password !== undefined) {\n\t\treturn { authorization: `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}` };\n\t}\n\treturn {};\n}\n\n/** Fetches the attestations with the user's registry credentials, sent to that origin only (spec DL-2). */\nexport const fetchAttestations: AttestationFetcher = async (url, config) => {\n\tconst dispatcher = dispatcherFor(config, url);\n\ttry {\n\t\tconst response = await request(url, {\n\t\t\tdispatcher,\n\t\t\theaders: { accept: 'application/json', ...authHeader(config) },\n\t\t});\n\t\tif (response.statusCode !== 200) {\n\t\t\tawait response.body.dump();\n\t\t\tthrow new Error(`registry answered ${response.statusCode} for ${url.pathname}`);\n\t\t}\n\t\tconst body = (await response.body.json()) as { attestations?: unknown };\n\t\tconst list = Array.isArray(body.attestations) ? body.attestations : [];\n\t\treturn list.filter(\n\t\t\t(item): item is Attestation =>\n\t\t\t\ttypeof item === 'object' &&\n\t\t\t\titem !== null &&\n\t\t\t\ttypeof (item as Attestation).predicateType === 'string' &&\n\t\t\t\t'bundle' in item,\n\t\t);\n\t} finally {\n\t\tawait dispatcher.close();\n\t}\n};\n\n/** sigstore's verifier with this repository's identity pinned; the TUF cache lives under the state dir. */\n/** sigstore matches the identity as an unanchored regular expression, so the exact SAN is escaped and anchored. */\nexport function identityPattern(identity: string = PROVENANCE_IDENTITY): string {\n\treturn `^${identity.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}$`;\n}\n\n/** The in-process verifier, run by the `verify-attestation` child command. */\nexport async function verifyBundleHere(bundle: unknown, tufCachePath: string): Promise<void> {\n\tconst sigstore = await import('sigstore');\n\tawait sigstore.verify(bundle as Parameters<typeof sigstore.verify>[0], {\n\t\tcertificateIssuer: PROVENANCE_ISSUER,\n\t\tcertificateIdentityURI: identityPattern(),\n\t\ttufCachePath,\n\t});\n}\n\n/** How to reach this program again from a child process: the entry argv plus the `cli` selector under the launcher. */\nexport function selfCommand(): string[] {\n\tconst entry = process.argv[1] ?? '';\n\treturn entry.endsWith('bootstrap.cjs') ? [entry, 'cli'] : [entry];\n}\n\n/**\n * Runs the verifier in a child Node (spec DL-2): sigstore reaches TUF through make-fetch-happen, which reads\n * proxies from the env, and Node reads NODE_EXTRA_CA_CERTS only at start. The child's env carries nothing else.\n */\nexport const verifyBundle: BundleVerifier = async (bundle, options) => {\n\tconst dir = mkdtempSync(join(options.tufCachePath, 'bundle-'));\n\tconst file = join(dir, 'bundle.json');\n\twriteFileSync(file, JSON.stringify(bundle), { mode: 0o600 });\n\tconst { args, env } = verifierLaunch(file, options, dir);\n\ttry {\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\texecFile(\n\t\t\t\tprocess.execPath,\n\t\t\t\targs,\n\t\t\t\t{ env, encoding: 'utf8', timeout: 300_000, windowsHide: true },\n\t\t\t\t(error, stdout, stderr) => {\n\t\t\t\t\tif (error === null) {\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\treject(\n\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t`${stderr.trim() || stdout.trim() || error.message}`.replace(/^npm-vm: /, ''),\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t} finally {\n\t\trmSync(dir, { recursive: true, force: true });\n\t}\n};\n\n/** The verifier child's argv and env for one bundle file; `dir` is private to this run and holds any CA bundle. */\nexport function verifierLaunch(\n\tfile: string,\n\toptions: Parameters<BundleVerifier>[1],\n\tdir: string,\n): { args: string[]; env: NodeJS.ProcessEnv } {\n\tconst [entry, ...prefix] = selfCommand();\n\treturn {\n\t\targs: [\n\t\t\tentry as string,\n\t\t\t...prefix,\n\t\t\t'verify-attestation',\n\t\t\t'--bundle',\n\t\t\tfile,\n\t\t\t'--tuf-cache',\n\t\t\toptions.tufCachePath,\n\t\t],\n\t\tenv: childEnv(options.config, options.env, dir),\n\t};\n}\n\nconst PROXY_KEYS = /^(https?_proxy|all_proxy|no_proxy|proxy|node_extra_ca_certs|node_options)$/i;\n\n/** The child's env: the parent's minus every proxy and Node override, plus only what the npm config says. */\nexport function childEnv(\n\tconfig: NpmConfigView,\n\tenv: NodeJS.ProcessEnv,\n\tbundleDir: string | null = null,\n): NodeJS.ProcessEnv {\n\tconst child: NodeJS.ProcessEnv = {};\n\tfor (const [key, value] of Object.entries(env)) {\n\t\tif (!PROXY_KEYS.test(key) && !/^npm_config_/i.test(key)) {\n\t\t\tchild[key] = value;\n\t\t}\n\t}\n\tconst httpsProxy = config.httpsProxy ?? config.proxy;\n\tif (httpsProxy !== null) {\n\t\tchild['https_proxy'] = httpsProxy;\n\t}\n\tif (config.proxy !== null) {\n\t\tchild['http_proxy'] = config.proxy;\n\t}\n\tif (config.noproxy !== null) {\n\t\tchild['no_proxy'] = config.noproxy;\n\t}\n\t// Inline `ca` has no file for NODE_EXTRA_CA_CERTS to point at; the child gets a private bundle of both.\n\tif (config.ca !== null && config.ca.length > 0 && bundleDir !== null) {\n\t\tconst bundle = join(bundleDir, 'ca-bundle.pem');\n\t\tconst parts = [...config.ca];\n\t\tif (config.cafile !== null) {\n\t\t\tparts.push(readFileSync(config.cafile, 'utf8'));\n\t\t}\n\t\twriteFileSync(bundle, `${parts.map((part) => part.trim()).join('\\n')}\\n`, { mode: 0o600 });\n\t\tchild['NODE_EXTRA_CA_CERTS'] = bundle;\n\t} else if (config.cafile !== null) {\n\t\tchild['NODE_EXTRA_CA_CERTS'] = config.cafile;\n\t}\n\treturn child;\n}\n\ninterface Statement {\n\tsubject: Array<{ name: string; digest: Record<string, string> }>;\n\tpredicateType: string;\n}\n\nfunction isSubject(value: unknown): value is Statement['subject'][number] {\n\tif (typeof value !== 'object' || value === null) {\n\t\treturn false;\n\t}\n\tconst { name, digest } = value as { name?: unknown; digest?: unknown };\n\treturn (\n\t\ttypeof name === 'string' &&\n\t\ttypeof digest === 'object' &&\n\t\tdigest !== null &&\n\t\t!Array.isArray(digest)\n\t);\n}\n\nfunction statementOf(bundle: unknown): Statement | null {\n\tconst payload = (bundle as { dsseEnvelope?: { payload?: unknown } }).dsseEnvelope?.payload;\n\tif (typeof payload !== 'string') {\n\t\treturn null;\n\t}\n\ttry {\n\t\tconst parsed = JSON.parse(\n\t\t\tBuffer.from(payload, 'base64').toString('utf8'),\n\t\t) as Partial<Statement>;\n\t\tif (typeof parsed !== 'object' || parsed === null || !Array.isArray(parsed.subject)) {\n\t\t\treturn null;\n\t\t}\n\t\treturn {\n\t\t\tpredicateType: typeof parsed.predicateType === 'string' ? parsed.predicateType : '',\n\t\t\tsubject: parsed.subject.filter(isSubject).map((subject) => ({\n\t\t\t\tname: subject.name,\n\t\t\t\tdigest: Object.fromEntries(\n\t\t\t\t\tObject.entries(subject.digest).filter(([, value]) => typeof value === 'string'),\n\t\t\t\t) as Record<string, string>,\n\t\t\t})),\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Verifies the SLSA provenance of a release (spec SUP-2): fetched from the registry origin, signed by this\n * repository's release workflow on main, and naming exactly this package version and tarball digest.\n */\nexport async function verifyProvenance(\n\tinput: ProvenanceInput,\n\tdeps: { fetch?: AttestationFetcher; verify?: BundleVerifier; env?: NodeJS.ProcessEnv } = {},\n): Promise<void> {\n\tconst { name, version } = input;\n\tlet url: URL;\n\ttry {\n\t\turl = attestationUrl(input, input.config.registry);\n\t} catch (error) {\n\t\tthrow failure(name, version, `bad attestation URL: ${redactUrls((error as Error).message)}`);\n\t}\n\tlet attestations: Attestation[];\n\ttry {\n\t\tattestations = await (deps.fetch ?? fetchAttestations)(url, input.config);\n\t} catch (error) {\n\t\tthrow failure(\n\t\t\tname,\n\t\t\tversion,\n\t\t\t`cannot fetch attestations: ${redactUrls((error as Error).message)}`,\n\t\t);\n\t}\n\tconst provenance = attestations.find((item) => item.predicateType === SLSA_PREDICATE);\n\tif (provenance === undefined) {\n\t\tthrow failure(name, version, 'the registry holds no SLSA provenance attestation for it');\n\t}\n\tconst statement = statementOf(provenance.bundle);\n\tif (statement === null) {\n\t\tthrow failure(name, version, 'the attestation bundle carries no readable in-toto statement');\n\t}\n\t// The registry's label is unsigned; the statement inside the envelope is what the signature covers.\n\tif (statement.predicateType !== SLSA_PREDICATE) {\n\t\tthrow failure(\n\t\t\tname,\n\t\t\tversion,\n\t\t\t`the signed statement is ${statement.predicateType}, not SLSA provenance`,\n\t\t);\n\t}\n\t// npm's provenance encodes the scope marker only: `pkg:npm/%40scope/name@version`.\n\tconst expectedSubject = `pkg:npm/${name.replace(/^@/, '%40')}@${version}`;\n\tconst subject = statement.subject.find((item) => item.name === expectedSubject);\n\tif (subject === undefined) {\n\t\tthrow failure(\n\t\t\tname,\n\t\t\tversion,\n\t\t\t`the attestation names ${statement.subject.map((item) => item.name).join(', ') || 'nothing'}, not ${expectedSubject}`,\n\t\t);\n\t}\n\tif (subject.digest['sha512'] !== input.sha512hex) {\n\t\tthrow failure(name, version, 'the attested tarball digest differs from the downloaded tarball');\n\t}\n\tconst tufCachePath = join(input.stateDir, 'sigstore');\n\tmkdirSync(tufCachePath, { recursive: true, mode: 0o700 });\n\ttry {\n\t\tawait (deps.verify ?? verifyBundle)(provenance.bundle, {\n\t\t\ttufCachePath,\n\t\t\tconfig: input.config,\n\t\t\tenv: deps.env ?? process.env,\n\t\t});\n\t} catch (error) {\n\t\tthrow failure(\n\t\t\tname,\n\t\t\tversion,\n\t\t\t`signature verification failed: ${redactUrls((error as Error).message)}`,\n\t\t);\n\t}\n}\n","import { execFile } from 'node:child_process';\nimport { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';\nimport { join } from 'node:path';\nimport semver from 'semver';\nimport { EXIT, NpmVmError } from '../errors.ts';\nimport { abiMessage } from '../messages.ts';\nimport { loadNpmConfig } from '../install/config.ts';\nimport { newWorkDir, Transport, transportUsable } from '../install/fetch.ts';\nimport { loadKeyring } from '../install/keys.ts';\nimport {\n\tverifyProvenance,\n\ttype AttestationFetcher,\n\ttype BundleVerifier,\n} from '../install/provenance.ts';\nimport { fileDigests, safeExtract, verifySignatures } from '../install/verify.ts';\nimport { findOwnNpm } from '../own-npm.ts';\nimport { transportMessage } from '../messages.ts';\nimport { atomicWrite } from '../state/atomic.ts';\nimport { mutateFile, recoverDeadJournals } from '../state/journal.ts';\nimport { acquireLock } from '../state/lock.ts';\nimport {\n\tBOOTSTRAP_FILE,\n\tinstallVersion,\n\tPREVIOUS_FILE,\n\treadCurrent,\n\treadPrevious,\n\truntimeAbi,\n\tversionDir,\n} from '../setup/layout.ts';\nimport { executionPolicy } from '../setup/profile.ts';\nimport {\n\tLAUNCHERS_DIR,\n\trenderShims,\n\tshimAbi,\n\tshimDir,\n\tstalePowershellShims,\n} from '../setup/shims.ts';\nimport { powershellAllowsScripts } from '../setup/windows.ts';\nimport type { CommandContext } from './context.ts';\n\nexport const PACKAGE_NAME = '@mawesome/npm-vm';\n\nexport interface SelfUpdateDeps {\n\tfetchAttestations?: AttestationFetcher;\n\tverifyBundle?: BundleVerifier;\n}\n\nexport interface SelfUpdateOptions {\n\trollback: boolean;\n}\n\nfunction run(\n\tfile: string,\n\targs: string[],\n): Promise<{ code: number | null; stdout: string; stderr: string }> {\n\treturn new Promise((resolve) => {\n\t\texecFile(\n\t\t\tprocess.execPath,\n\t\t\t[file, ...args],\n\t\t\t{ encoding: 'utf8', timeout: 60_000, windowsHide: true },\n\t\t\t(error, stdout, stderr) => {\n\t\t\t\tresolve({\n\t\t\t\t\tcode:\n\t\t\t\t\t\terror === null\n\t\t\t\t\t\t\t? 0\n\t\t\t\t\t\t\t: (((error as { code?: number | string }).code as number | null) ?? 1),\n\t\t\t\t\tstdout,\n\t\t\t\t\tstderr,\n\t\t\t\t});\n\t\t\t},\n\t\t);\n\t});\n}\n\n/** The launcher generation a bootstrap file belongs to, read from its `LAUNCHER_ABI` constant. */\nexport function launcherAbiOf(bootstrapFile: string): number {\n\tconst abi = shimAbi(readFileSync(bootstrapFile, 'utf8'));\n\tif (abi === null) {\n\t\tthrow new NpmVmError(\n\t\t\t'M-ABI',\n\t\t\tEXIT.abi,\n\t\t\tabiMessage(`${bootstrapFile} declares no launcher ABI`),\n\t\t);\n\t}\n\treturn abi;\n}\n\n/**\n * Replaces the home's launcher files with those of `version` (spec SUP-3): the bootstrap at the root and\n * every shim, rendered from that version's templates, each under a journal.\n */\nexport function installLaunchers(context: CommandContext, version: string): void {\n\tconst { dirs, platform, env } = context;\n\tconst dir = versionDir(dirs.home, version);\n\tconst bootstrap = join(dir, BOOTSTRAP_FILE);\n\tconst abi = launcherAbiOf(bootstrap);\n\tmutateFile(\n\t\tdirs.journal,\n\t\t'launcher',\n\t\tcontext.owner,\n\t\tjoin(dirs.home, BOOTSTRAP_FILE),\n\t\treadFileSync(bootstrap),\n\t\t0o644,\n\t);\n\tconst powershell = platform !== 'win32' || powershellAllowsScripts(executionPolicy(env));\n\tmkdirSync(shimDir(dirs.home), { recursive: true, mode: 0o755 });\n\tfor (const file of renderShims(dirs.home, platform, {\n\t\tpowershell,\n\t\ttemplates: join(dir, LAUNCHERS_DIR),\n\t\tabi,\n\t})) {\n\t\tmutateFile(\n\t\t\tdirs.journal,\n\t\t\t'launcher',\n\t\t\tcontext.owner,\n\t\t\tjoin(shimDir(dirs.home), file.name),\n\t\t\tBuffer.from(file.content),\n\t\t\tfile.mode,\n\t\t);\n\t}\n\tif (platform === 'win32' && !powershell) {\n\t\tfor (const stale of stalePowershellShims(dirs.home)) {\n\t\t\tmutateFile(dirs.journal, 'launcher', context.owner, stale, null);\n\t\t}\n\t}\n}\n\nexport function currentLauncherAbi(context: CommandContext): number | null {\n\tconst file = join(context.dirs.home, BOOTSTRAP_FILE);\n\treturn existsSync(file) ? shimAbi(readFileSync(file, 'utf8')) : null;\n}\n\nexport async function selfUpdate(\n\tcontext: CommandContext,\n\toptions: SelfUpdateOptions,\n\tdeps: SelfUpdateDeps = {},\n): Promise<number> {\n\tconst lock = await acquireLock(context.dirs.state, context.owner);\n\ttry {\n\t\trecoverDeadJournals(context.dirs.journal, context.dirs.machine.id);\n\t\treturn options.rollback ? rollback(context) : await update(context, deps);\n\t} finally {\n\t\tlock.release();\n\t}\n}\n\n/** `self-update --rollback` (spec SUP-4): offline, swaps `current` back and restores the previous launchers if the ABI differs. */\nfunction rollback(context: CommandContext): number {\n\tconst { dirs, io } = context;\n\tconst current = readCurrent(dirs.home);\n\tconst previous = readPrevious(dirs.home);\n\tif (previous === null || !existsSync(versionDir(dirs.home, previous)) || current === null) {\n\t\tthrow new NpmVmError('M-ABI', EXIT.usage, 'No previous version to roll back to.');\n\t}\n\t// The newer launcher still runs the previous runtime, so `current` moves first; the older launcher could not run the newer runtime.\n\tmutateFile(\n\t\tdirs.journal,\n\t\t'launcher',\n\t\tcontext.owner,\n\t\tjoin(dirs.home, 'current'),\n\t\tBuffer.from(`${previous}\\n`),\n\t);\n\tif (\n\t\tlauncherAbiOf(join(versionDir(dirs.home, previous), BOOTSTRAP_FILE)) !==\n\t\tcurrentLauncherAbi(context)\n\t) {\n\t\tinstallLaunchers(context, previous);\n\t}\n\tatomicWrite(join(dirs.home, PREVIOUS_FILE), `${current}\\n`);\n\tio.out(\n\t\tcontext.json\n\t\t\t? JSON.stringify({ current: previous, previous: current })\n\t\t\t: `Rolled back to npm-vm ${previous} (from ${current}).`,\n\t);\n\treturn EXIT.ok;\n}\n\nasync function update(context: CommandContext, deps: SelfUpdateDeps): Promise<number> {\n\tconst { dirs, env, io } = context;\n\tconst installed = readCurrent(dirs.home) ?? context.version;\n\tconst own = findOwnNpm();\n\tconst found = own?.version ?? null;\n\tif (!transportUsable(own)) {\n\t\tthrow new NpmVmError(\n\t\t\t'M-TRANSPORT',\n\t\t\tEXIT.transport,\n\t\t\ttransportMessage(found, 'too old or missing'),\n\t\t);\n\t}\n\tconst work = newWorkDir(dirs.tmp);\n\ttry {\n\t\tconst config = await loadNpmConfig(own, env, work);\n\t\tconst transport = new Transport(own, config, env, dirs.tmp);\n\t\tconst latest = (await transport.viewPackage(PACKAGE_NAME, 'latest'))[0];\n\t\tif (latest === undefined) {\n\t\t\tthrow new NpmVmError(\n\t\t\t\t'M-TRANSPORT',\n\t\t\t\tEXIT.transport,\n\t\t\t\ttransportMessage(own.version, `${PACKAGE_NAME}@latest is not published`),\n\t\t\t);\n\t\t}\n\t\t// Forward-only (SUP-1): a registry that serves an older \"latest\" cannot move the install back.\n\t\tif (!semver.gt(latest.version, installed)) {\n\t\t\tio.out(\n\t\t\t\tcontext.json\n\t\t\t\t\t? JSON.stringify({ current: installed, latest: latest.version, updated: false })\n\t\t\t\t\t: `npm-vm ${installed} is up to date (latest is ${latest.version}).`,\n\t\t\t);\n\t\t\treturn EXIT.ok;\n\t\t}\n\t\tconst packed = await transport.packPackage(PACKAGE_NAME, latest.version, work);\n\t\tconst digests = await fileDigests(packed.file);\n\t\tif (digests.sha512 !== latest.integrity) {\n\t\t\tthrow new NpmVmError(\n\t\t\t\t'M-INTEGRITY',\n\t\t\t\tEXIT.verification,\n\t\t\t\t`${PACKAGE_NAME}@${latest.version}: tarball does not match the registry integrity.`,\n\t\t\t);\n\t\t}\n\t\tawait verifySignatures({\n\t\t\tname: PACKAGE_NAME,\n\t\t\tversion: latest.version,\n\t\t\tintegrity: latest.integrity,\n\t\t\tsignatures: latest.signatures,\n\t\t\tpublishedAt: async () => null,\n\t\t\tkeys: loadKeyring(dirs.state),\n\t\t\tregistry: config.registry,\n\t\t\tpinned: false,\n\t\t});\n\t\tawait verifyProvenance(\n\t\t\t{\n\t\t\t\tname: PACKAGE_NAME,\n\t\t\t\tversion: latest.version,\n\t\t\t\tsha512hex: digests.sha512hex,\n\t\t\t\tattestationsUrl: latest.attestationsUrl,\n\t\t\t\tconfig,\n\t\t\t\tstateDir: dirs.state,\n\t\t\t},\n\t\t\t{\n\t\t\t\t...(deps.fetchAttestations === undefined ? {} : { fetch: deps.fetchAttestations }),\n\t\t\t\t...(deps.verifyBundle === undefined ? {} : { verify: deps.verifyBundle }),\n\t\t\t\tenv,\n\t\t\t},\n\t\t);\n\t\tconst extracted = join(work, 'package');\n\t\tmkdirSync(extracted, { mode: 0o700 });\n\t\tawait safeExtract(packed.file, extracted);\n\t\tconst runtimeSource = join(extracted, 'dist', 'runtime');\n\t\tif (\n\t\t\t!existsSync(join(runtimeSource, 'runtime.cjs')) ||\n\t\t\t!existsSync(join(runtimeSource, BOOTSTRAP_FILE))\n\t\t) {\n\t\t\tthrow new NpmVmError(\n\t\t\t\t'M-INTEGRITY',\n\t\t\t\tEXIT.verification,\n\t\t\t\t`${PACKAGE_NAME}@${latest.version} ships no runtime build.`,\n\t\t\t);\n\t\t}\n\t\tconst candidateAbi = launcherAbiOf(join(runtimeSource, BOOTSTRAP_FILE));\n\t\tconst installedRuntimeAbi =\n\t\t\truntimeAbi(dirs.home, installed) ?? currentLauncherAbi(context) ?? candidateAbi;\n\t\tif (installedRuntimeAbi < candidateAbi - 1) {\n\t\t\tthrow new NpmVmError(\n\t\t\t\t'M-ABI',\n\t\t\t\tEXIT.abi,\n\t\t\t\tabiMessage(\n\t\t\t\t\t`npm-vm ${latest.version} skips launcher generations (${installedRuntimeAbi} to ${candidateAbi})`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\t// The launcher is swapped before `current`: one older than the installed runtime would break every shim meanwhile.\n\t\tif (candidateAbi < installedRuntimeAbi) {\n\t\t\tthrow new NpmVmError(\n\t\t\t\t'M-ABI',\n\t\t\t\tEXIT.abi,\n\t\t\t\tabiMessage(\n\t\t\t\t\t`npm-vm ${latest.version} ships launcher ABI ${candidateAbi}, older than the installed runtime's ${installedRuntimeAbi}`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tconst target = installVersion(dirs.home, latest.version, runtimeSource, candidateAbi);\n\t\tconst health = await run(join(target, BOOTSTRAP_FILE), ['--candidate', 'cli', '--version']);\n\t\tif (health.code !== 0 || health.stdout.trim() !== latest.version) {\n\t\t\trmSync(target, { recursive: true, force: true });\n\t\t\tthrow new NpmVmError(\n\t\t\t\t'M-ABI',\n\t\t\t\tEXIT.abi,\n\t\t\t\tabiMessage(\n\t\t\t\t\t`the downloaded runtime failed its health check: ${health.stderr.trim() || health.stdout.trim() || `exit ${health.code}`}`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tif (candidateAbi !== currentLauncherAbi(context)) {\n\t\t\tinstallLaunchers(context, latest.version);\n\t\t}\n\t\tatomicWrite(join(dirs.home, PREVIOUS_FILE), `${installed}\\n`);\n\t\tmutateFile(\n\t\t\tdirs.journal,\n\t\t\t'launcher',\n\t\t\tcontext.owner,\n\t\t\tjoin(dirs.home, 'current'),\n\t\t\tBuffer.from(`${latest.version}\\n`),\n\t\t);\n\t\tio.out(\n\t\t\tcontext.json\n\t\t\t\t? JSON.stringify({ current: latest.version, previous: installed, updated: true })\n\t\t\t\t: `Updated npm-vm ${installed} to ${latest.version}.`,\n\t\t);\n\t\treturn EXIT.ok;\n\t} finally {\n\t\trmSync(work, { recursive: true, force: true });\n\t}\n}\n","import { chmodSync, existsSync, mkdirSync, readFileSync, statSync } from 'node:fs';\nimport { basename, join } from 'node:path';\nimport { EXIT, NpmVmError } from '../errors.ts';\nimport { dirPermsMessage, restartMessage } from '../messages.ts';\nimport { recoverDeadJournals, mutateFile } from '../state/journal.ts';\nimport { acquireLock } from '../state/lock.ts';\nimport { findNodeInstalls, linkOne, linkTargets, type LinkResult } from '../setup/link.ts';\nimport {\n\tBOOTSTRAP_FILE,\n\tinstallBootstrap,\n\tinstallVersion,\n\treadCurrent,\n\treadManifest,\n\truntimeDistDir,\n\tsetCurrent,\n\tsweepReplaced,\n\tversionDir,\n} from '../setup/layout.ts';\nimport {\n\tapplyProfileEdit,\n\texecutionPolicy,\n\tplanProfileEdit,\n\tprofileGuard,\n\tprofileTargets,\n\ttype ProfileTarget,\n} from '../setup/profile.ts';\nimport { isShell, profileBlock, type Shell } from '../setup/shell.ts';\nimport {\n\tassertSafeHome,\n\trenderShims,\n\tSHIM_ABI,\n\tshimDir,\n\tstalePowershellShims,\n} from '../setup/shims.ts';\nimport { addToUserPath, powershellAllowsScripts, setCmdAutoRun } from '../setup/windows.ts';\nimport type { CommandContext } from './context.ts';\nimport { doctor } from './doctor.ts';\n\nexport interface SetupOptions {\n\tlink: boolean;\n\tshells: Shell[] | null;\n\tyes: boolean;\n\tdryRun: boolean;\n\tmodifyProfile: boolean;\n\tcmdAutorun: boolean;\n\tstrict: boolean;\n\t/** Write the Windows user PATH and AutoRun; the Action turns this off and relies on GITHUB_PATH. */\n\tuserPath: boolean;\n}\n\nexport interface SetupReport {\n\thome: string;\n\tversion: string;\n\tprofiles: Array<{\n\t\tfile: string;\n\t\toutcome: 'written' | 'unchanged' | 'printed' | 'declined' | 'changed' | 'dry-run';\n\t\treason?: string;\n\t}>;\n\tlinks: LinkResult[];\n\tskipped: number;\n}\n\n/** Refuses a home or cache another user could write to (spec SEC-9). */\nexport function assertPrivateDir(dir: string, platform: NodeJS.Platform): void {\n\tif (platform === 'win32') {\n\t\treturn;\n\t}\n\tconst stat = statSync(dir);\n\tif (process.getuid !== undefined && stat.uid !== process.getuid()) {\n\t\tthrow new NpmVmError(\n\t\t\t'M-DIRPERMS',\n\t\t\tEXIT.problems,\n\t\t\tdirPermsMessage(dir, 'is not owned by you', `chown $(id -u) ${dir}`),\n\t\t);\n\t}\n\tif ((stat.mode & 0o022) !== 0) {\n\t\tthrow new NpmVmError(\n\t\t\t'M-DIRPERMS',\n\t\t\tEXIT.problems,\n\t\t\tdirPermsMessage(dir, 'is writable by other users', `chmod go-w ${dir}`),\n\t\t);\n\t}\n}\n\nfunction ensurePrivateDir(dir: string, platform: NodeJS.Platform): void {\n\tif (!existsSync(dir)) {\n\t\tmkdirSync(dir, { recursive: true, mode: 0o700 });\n\t\tif (platform !== 'win32') {\n\t\t\tchmodSync(dir, 0o700);\n\t\t}\n\t}\n\tassertPrivateDir(dir, platform);\n}\n\n/** The shells to configure: `--shell` values, else the login shell, plus PowerShell on Windows. */\nexport function defaultShells(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): Shell[] {\n\tif (platform === 'win32') {\n\t\treturn ['powershell'];\n\t}\n\tconst login = basename(env['SHELL'] ?? '');\n\treturn isShell(login) ? [login] : ['bash'];\n}\n\nfunction sameFiles(home: string, version: string, distDir: string): boolean {\n\tconst manifest = readManifest(home, version);\n\tif (manifest === null) {\n\t\treturn false;\n\t}\n\treturn manifest.files.every((file) => {\n\t\ttry {\n\t\t\treturn readFileSync(join(distDir, file)).equals(\n\t\t\t\treadFileSync(join(versionDir(home, version), file)),\n\t\t\t);\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t});\n}\n\nexport async function setup(context: CommandContext, options: SetupOptions): Promise<number> {\n\tconst { dirs, env, platform, io } = context;\n\tassertSafeHome(dirs.home);\n\tconst distDir = runtimeDistDir();\n\tif (distDir === null) {\n\t\tthrow new NpmVmError(\n\t\t\t'M-ABI',\n\t\t\tEXIT.problems,\n\t\t\t'This npm-vm installation ships no runtime build; reinstall the package.',\n\t\t);\n\t}\n\tfor (const dir of [dirs.home, dirs.state, dirs.cache]) {\n\t\tif (options.dryRun) {\n\t\t\tif (existsSync(dir)) {\n\t\t\t\tassertPrivateDir(dir, platform);\n\t\t\t}\n\t\t} else {\n\t\t\tensurePrivateDir(dir, platform);\n\t\t}\n\t}\n\tconst report: SetupReport = {\n\t\thome: dirs.home,\n\t\tversion: context.version,\n\t\tprofiles: [],\n\t\tlinks: [],\n\t\tskipped: 0,\n\t};\n\tconst shells = options.shells ?? defaultShells(env, platform);\n\tconst targets = options.modifyProfile ? profileTargets(shells, env, platform) : [];\n\tconst policy = platform === 'win32' ? executionPolicy(env) : null;\n\tconst powershell = platform !== 'win32' || powershellAllowsScripts(policy);\n\n\t// Every target is examined before anything is written, so a refusal costs nothing.\n\tconst plans = targets.map((target) => ({\n\t\ttarget,\n\t\tguard: profileGuard(target.file, env, platform),\n\t\tedit: planProfileEdit(target, dirs.home),\n\t}));\n\n\t// A dry run writes nothing, not even the lock, so the home stays absent when it did not exist.\n\tconst lock = options.dryRun ? null : await acquireLock(dirs.state, context.owner);\n\ttry {\n\t\tif (lock !== null) {\n\t\t\trecoverDeadJournals(dirs.journal, dirs.machine.id);\n\t\t}\n\t\tif (!options.dryRun) {\n\t\t\tinstallRuntime(context, distDir);\n\t\t\tmkdirSync(shimDir(dirs.home), { recursive: true, mode: 0o755 });\n\t\t\tfor (const file of renderShims(dirs.home, platform, { powershell })) {\n\t\t\t\tmutateFile(\n\t\t\t\t\tdirs.journal,\n\t\t\t\t\t'launcher',\n\t\t\t\t\tcontext.owner,\n\t\t\t\t\tjoin(shimDir(dirs.home), file.name),\n\t\t\t\t\tBuffer.from(file.content),\n\t\t\t\t\tfile.mode,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (platform === 'win32' && !powershell) {\n\t\t\t\tfor (const stale of stalePowershellShims(dirs.home)) {\n\t\t\t\t\tmutateFile(dirs.journal, 'launcher', context.owner, stale, null);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (const plan of plans) {\n\t\t\treport.profiles.push(await applyPlan(context, options, plan));\n\t\t}\n\t\tif (options.link) {\n\t\t\tfor (const install of findNodeInstalls(env, platform)) {\n\t\t\t\tfor (const target of linkTargets(dirs.home, platform, powershell)) {\n\t\t\t\t\tif (options.dryRun) {\n\t\t\t\t\t\treport.links.push({\n\t\t\t\t\t\t\ttarget: join(install.binDir, target.name),\n\t\t\t\t\t\t\toutcome: 'linked',\n\t\t\t\t\t\t\tdetail: 'dry run',\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\treport.links.push(linkOne(dirs, context.owner, install.binDir, target));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (platform === 'win32' && !options.dryRun && options.userPath) {\n\t\t\tif (addToUserPath(env, shimDir(dirs.home))) {\n\t\t\t\tenv['Path'] = `${shimDir(dirs.home)};${env['Path'] ?? ''}`;\n\t\t\t\tio.err(restartMessage());\n\t\t\t}\n\t\t\tif (options.cmdAutorun) {\n\t\t\t\tsetCmdAutoRun(env, shimDir(dirs.home));\n\t\t\t}\n\t\t\tif (!powershell) {\n\t\t\t\tio.err(\n\t\t\t\t\t`PowerShell's execution policy (${policy ?? 'unknown'}) blocks unsigned scripts, so no .ps1 shims were installed; cmd shims take over.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tlock?.release();\n\t}\n\treport.skipped =\n\t\treport.profiles.filter(\n\t\t\t(entry) =>\n\t\t\t\tentry.outcome === 'printed' || entry.outcome === 'declined' || entry.outcome === 'changed',\n\t\t).length +\n\t\treport.links.filter((link) => ['foreign', 'unwritable', 'missing'].includes(link.outcome))\n\t\t\t.length;\n\tif (context.json) {\n\t\tio.out(JSON.stringify(report, null, 2));\n\t} else {\n\t\tio.out(describe(report));\n\t}\n\tif (!options.dryRun) {\n\t\t// With --json the setup report is the only document on stdout; doctor still decides --strict.\n\t\tconst health = await doctor(context, { quiet: context.json });\n\t\tif (health !== EXIT.ok && options.strict) {\n\t\t\treturn EXIT.partial;\n\t\t}\n\t}\n\treturn options.strict && report.skipped > 0 ? EXIT.partial : EXIT.ok;\n}\n\n/** Installs this version's runtime and launcher unless the identical files are already in place. */\nfunction installRuntime(context: CommandContext, distDir: string): void {\n\tconst { dirs, version } = context;\n\tif (!sameFiles(dirs.home, version, distDir)) {\n\t\tinstallVersion(dirs.home, version, distDir, SHIM_ABI);\n\t}\n\tsweepReplaced(dirs.home);\n\tif (readCurrent(dirs.home) !== version) {\n\t\tmutateFile(\n\t\t\tdirs.journal,\n\t\t\t'launcher',\n\t\t\tcontext.owner,\n\t\t\tjoin(dirs.home, 'current'),\n\t\t\tBuffer.from(`${version}\\n`),\n\t\t);\n\t}\n\tconst bootstrap = readFileSync(join(versionDir(dirs.home, version), BOOTSTRAP_FILE));\n\tconst installed = existsSync(join(dirs.home, BOOTSTRAP_FILE))\n\t\t? readFileSync(join(dirs.home, BOOTSTRAP_FILE))\n\t\t: null;\n\tif (installed === null || !installed.equals(bootstrap)) {\n\t\tmutateFile(\n\t\t\tdirs.journal,\n\t\t\t'launcher',\n\t\t\tcontext.owner,\n\t\t\tjoin(dirs.home, BOOTSTRAP_FILE),\n\t\t\tbootstrap,\n\t\t\t0o644,\n\t\t);\n\t}\n\tvoid setCurrent;\n\tvoid installBootstrap;\n}\n\nasync function applyPlan(\n\tcontext: CommandContext,\n\toptions: SetupOptions,\n\tplan: { target: ProfileTarget; guard: string | null; edit: ReturnType<typeof planProfileEdit> },\n): Promise<SetupReport['profiles'][number]> {\n\tconst { io, dirs } = context;\n\tconst { target } = plan;\n\tif (plan.guard !== null) {\n\t\tio.out(\n\t\t\t`Not editing ${target.file}: ${plan.guard}. Add this yourself:\\n${profileBlock(target.shell, dirs.home, target.parts)}`,\n\t\t);\n\t\treturn { file: target.file, outcome: 'printed', reason: plan.guard };\n\t}\n\tif (plan.edit === null) {\n\t\treturn { file: target.file, outcome: 'unchanged' };\n\t}\n\tif (options.dryRun) {\n\t\tio.out(`Would edit ${target.file}:\\n${plan.edit.diff}`);\n\t\treturn { file: target.file, outcome: 'dry-run' };\n\t}\n\tif (!options.yes) {\n\t\tio.out(plan.edit.diff);\n\t\tconst agreed = await io.confirm(`Apply this change to ${target.file}?`);\n\t\tif (!agreed) {\n\t\t\tio.out(\n\t\t\t\t`Skipped ${target.file}. Add this yourself:\\n${profileBlock(target.shell, dirs.home, target.parts)}`,\n\t\t\t);\n\t\t\treturn { file: target.file, outcome: 'declined' };\n\t\t}\n\t}\n\t/* The file may have changed while the prompt was open: guard and plan again, and never write over what was not shown.\n\t * The guard runs again because a swap for a symlink keeps the content equal (spec SH-5). */\n\tconst guard = profileGuard(target.file, context.env, context.platform);\n\tconst fresh = planProfileEdit(target, dirs.home);\n\tif (fresh === null) {\n\t\treturn { file: target.file, outcome: 'unchanged' };\n\t}\n\tif (guard !== null || (fresh.before !== plan.edit.before && !options.yes)) {\n\t\tio.out(\n\t\t\t`${target.file} changed while the prompt was open; run setup again to review the new change.`,\n\t\t);\n\t\treturn { file: target.file, outcome: 'changed' };\n\t}\n\tapplyProfileEdit(dirs, context.owner, fresh);\n\treturn { file: target.file, outcome: 'written' };\n}\n\nfunction describe(report: SetupReport): string {\n\tconst lines = [`npm-vm ${report.version} installed in ${report.home}`];\n\tfor (const profile of report.profiles) {\n\t\tlines.push(\n\t\t\t` ${profile.file}: ${profile.outcome}${profile.reason ? ` (${profile.reason})` : ''}`,\n\t\t);\n\t}\n\tfor (const link of report.links) {\n\t\tlines.push(` ${link.target}: ${link.outcome}${link.detail ? ` (${link.detail})` : ''}`);\n\t}\n\treturn lines.join('\\n');\n}\n","import { rmdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { atomicRename, removeWithRetry } from '../state/atomic.ts';\nimport { EXIT } from '../errors.ts';\nimport { ENTRIES_DIR, stagingDir } from '../install/cache.ts';\nimport { changedMessage } from '../messages.ts';\nimport { recoverDeadJournals } from '../state/journal.ts';\nimport { acquireLock } from '../state/lock.ts';\nimport { pruneCache } from '../state/prune.ts';\nimport { readLinks, unlinkOne } from '../setup/link.ts';\nimport { readProfiles, removeProfileBlock } from '../setup/profile.ts';\nimport { shimDir } from '../setup/shims.ts';\nimport { clearCmdAutoRun, removeFromUserPath } from '../setup/windows.ts';\nimport type { CommandContext } from './context.ts';\n\nexport interface UninstallOptions {\n\tyes: boolean;\n\tpurgeCache: boolean;\n}\n\nexport interface UninstallReport {\n\tprofiles: Array<{ file: string; outcome: string }>;\n\tlinks: Array<{ target: string; outcome: string }>;\n\thomeRemoved: boolean;\n\tcacheRemoved: boolean;\n\t/** Entries `--purge-cache` left because a running npm holds them. */\n\tcacheKept: string[];\n}\n\n/** Removes the cache's directories only while empty: an npm publishing right now keeps its entry. */\nfunction removeEmptyTree(cache: string): void {\n\tfor (const dir of [join(cache, ENTRIES_DIR), stagingDir(cache), cache]) {\n\t\ttry {\n\t\t\trmdirSync(dir);\n\t\t} catch {\n\t\t\t// Not empty or already gone; either way it stays as it is.\n\t\t}\n\t}\n}\n\nexport async function uninstall(\n\tcontext: CommandContext,\n\toptions: UninstallOptions,\n): Promise<number> {\n\tconst { dirs, env, platform, io } = context;\n\tif (!options.yes) {\n\t\tconst agreed = await io.confirm(\n\t\t\t`Remove npm-vm from ${dirs.home}, its profile blocks and links${options.purgeCache ? ', and the cache' : ''}?`,\n\t\t);\n\t\tif (!agreed) {\n\t\t\tio.out('Nothing removed.');\n\t\t\treturn EXIT.ok;\n\t\t}\n\t}\n\tconst report: UninstallReport = {\n\t\tprofiles: [],\n\t\tlinks: [],\n\t\thomeRemoved: false,\n\t\tcacheRemoved: false,\n\t\tcacheKept: [],\n\t};\n\tconst lock = await acquireLock(dirs.state, context.owner);\n\tlet clean = true;\n\ttry {\n\t\trecoverDeadJournals(dirs.journal, dirs.machine.id);\n\t\tfor (const entry of readProfiles(dirs).entries) {\n\t\t\tconst outcome = removeProfileBlock(dirs, context.owner, entry);\n\t\t\treport.profiles.push({ file: entry.file, outcome });\n\t\t\tif (outcome === 'changed') {\n\t\t\t\tclean = false;\n\t\t\t\tio.err(changedMessage(entry.file, 'npm-vm block'));\n\t\t\t}\n\t\t}\n\t\tfor (const entry of readLinks(dirs).entries) {\n\t\t\tconst outcome = unlinkOne(dirs, context.owner, entry);\n\t\t\treport.links.push({ target: entry.target, outcome });\n\t\t\tif (outcome === 'changed') {\n\t\t\t\tclean = false;\n\t\t\t\tio.err(changedMessage(entry.target, 'shim'));\n\t\t\t}\n\t\t}\n\t\tif (platform === 'win32') {\n\t\t\tremoveFromUserPath(env, shimDir(dirs.home));\n\t\t\tclearCmdAutoRun(env);\n\t\t}\n\t\tif (options.purgeCache) {\n\t\t\t// Through the gate and lease protocol, under the home lock and the cache's own lock, which other homes share.\n\t\t\tconst cacheLock = await acquireLock(dirs.cache, context.owner);\n\t\t\ttry {\n\t\t\t\tconst pruned = pruneCache(dirs.cache, context.owner, { maxAgeMs: 0 });\n\t\t\t\treport.cacheKept = pruned.kept.concat(pruned.skipped);\n\t\t\t\tif (report.cacheKept.length === 0) {\n\t\t\t\t\tremoveEmptyTree(dirs.cache);\n\t\t\t\t\treport.cacheRemoved = true;\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tcacheLock.release();\n\t\t\t}\n\t\t\tif (report.cacheRemoved) {\n\t\t\t\t// The lock file itself kept the root; now it can go too.\n\t\t\t\tremoveEmptyTree(dirs.cache);\n\t\t\t}\n\t\t\tif (report.cacheKept.length > 0) {\n\t\t\t\tclean = false;\n\t\t\t\tio.err(\n\t\t\t\t\t`Cache kept: ${report.cacheKept.join(', ')} ${report.cacheKept.length === 1 ? 'is' : 'are'} in use by a running npm.`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\t// Under the lock the home moves aside in one rename, so a setup that follows never writes into a dir being deleted.\n\t\tconst tombstone = `${dirs.home}.removing.${process.pid}.${Date.now()}`;\n\t\tatomicRename(dirs.home, tombstone);\n\t\tremoveWithRetry(tombstone);\n\t\treport.homeRemoved = true;\n\t} finally {\n\t\tlock.release();\n\t}\n\tio.out(context.json ? JSON.stringify(report, null, 2) : describe(report, dirs.cache));\n\treturn clean ? EXIT.ok : EXIT.problems;\n}\n\nfunction describe(report: UninstallReport, cache: string): string {\n\tconst lines = ['npm-vm removed.'];\n\tfor (const profile of report.profiles) {\n\t\tlines.push(` ${profile.file}: ${profile.outcome}`);\n\t}\n\tfor (const link of report.links) {\n\t\tlines.push(` ${link.target}: ${link.outcome}`);\n\t}\n\tif (report.cacheRemoved) {\n\t\tlines.push(` cache removed (${cache})`);\n\t} else if (report.cacheKept.length > 0) {\n\t\tlines.push(` cache kept at ${cache}: ${report.cacheKept.join(', ')} in use by a running npm`);\n\t} else {\n\t\tlines.push(` cache kept at ${cache}; add --purge-cache to remove it`);\n\t}\n\treturn lines.join('\\n');\n}\n","import { readFileSync } from 'node:fs';\nimport { parseArgs } from 'node:util';\nimport { EXIT, isNpmVmError } from '../errors.ts';\nimport { resolveNpm, type ResolveResult } from '../index.ts';\nimport { isShell, profileBlock, SHELLS, type Shell } from '../setup/shell.ts';\nimport { cacheList, cachePrune, DEFAULT_PRUNE_DAYS, install, recover } from './cache.ts';\nimport { createCommandContext, type CommandContext, type CommandIo } from './context.ts';\nimport { doctor } from './doctor.ts';\nimport { pin } from './pin.ts';\nimport { selfUpdate } from './self-update.ts';\nimport { setup } from './setup.ts';\nimport { uninstall } from './uninstall.ts';\n\nconst VERSION = readSelfVersion();\n\nconst USAGE = `npm-vm v${VERSION}: run the npm version a project declares in devEngines\n\nUsage:\n npm-vm <command> [options]\n\nCommands:\n setup Install the launcher, shims and shell snippets; --link also replaces npm\n inside every nvm/fnm Node. --shell <s> (repeatable), --yes, --dry-run,\n --no-modify-profile, --cmd-autorun and --no-user-path (Windows), --strict (exit 2 on skips).\n init <shell> Print the snippet for zsh, bash, fish or powershell (--path, --hook; default both).\n doctor Check the installation; exit 1 when something needs fixing.\n which Print the npm that would run for the current directory.\n pin [<range>] Write devEngines.packageManager for npm into the project's package.json.\n install [<spec>] Download and verify the project's npm, or <spec>, into the cache.\n cache list List cached npm versions.\n cache prune Remove unused entries; --older-than <days> (default ${DEFAULT_PRUNE_DAYS}).\n self-update Update npm-vm with provenance verification; --rollback restores the previous version.\n recover Finish a journal left by another machine: --journal <id> --confirm-dead-machine <id>.\n uninstall Remove npm-vm (--yes to skip the prompt, --purge-cache to drop the cache too).\n\nGlobal options:\n --json Machine-readable output where a command offers it.\n --version, -v Print the version.\n --help, -h Print this help.\n\nEnvironment:\n NPM_VM_VERSION Use this range or version instead of the project's.\n NPM_VM_DISABLE Any value: always run Node's own npm.\n NPM_VM_OFFLINE Any value: never contact the registry.\n NPM_VM_HOME The home directory (setup only).\n\nExit codes: 0 ok, 1 problems found, 2 partial setup under --strict, 3 resolution failed, 4 transport\nunavailable, 5 verification failed, 6 launcher mismatch, 64 usage error.`;\n\nexport interface DispatchOptions {\n\t/** The home the launcher runs from; the bin entry leaves it to the env and defaults. */\n\thome?: string;\n\tio?: CommandIo;\n\tenv?: NodeJS.ProcessEnv;\n}\n\nfunction parse(argv: string[]) {\n\treturn parseArgs({\n\t\targs: argv,\n\t\tallowPositionals: true,\n\t\tallowNegative: true,\n\t\toptions: {\n\t\t\tjson: { type: 'boolean' },\n\t\t\tpath: { type: 'boolean' },\n\t\t\thook: { type: 'boolean' },\n\t\t\tlink: { type: 'boolean' },\n\t\t\tshell: { type: 'string', multiple: true },\n\t\t\tyes: { type: 'boolean' },\n\t\t\t'dry-run': { type: 'boolean' },\n\t\t\t'modify-profile': { type: 'boolean' },\n\t\t\t'cmd-autorun': { type: 'boolean' },\n\t\t\t'user-path': { type: 'boolean' },\n\t\t\tstrict: { type: 'boolean' },\n\t\t\t'older-than': { type: 'string' },\n\t\t\trollback: { type: 'boolean' },\n\t\t\tjournal: { type: 'string' },\n\t\t\t'confirm-dead-machine': { type: 'string' },\n\t\t\t'purge-cache': { type: 'boolean' },\n\t\t\tbundle: { type: 'string' },\n\t\t\t'tuf-cache': { type: 'string' },\n\t\t\tversion: { type: 'boolean', short: 'v' },\n\t\t\thelp: { type: 'boolean', short: 'h' },\n\t\t},\n\t});\n}\n\ntype Values = ReturnType<typeof parse>['values'];\n\n/** Command-specific options, so a flag meant for another command is an error rather than silently ignored. */\nconst COMMAND_OPTIONS: Record<string, readonly (keyof Values)[]> = {\n\tsetup: [\n\t\t'link',\n\t\t'shell',\n\t\t'yes',\n\t\t'dry-run',\n\t\t'modify-profile',\n\t\t'cmd-autorun',\n\t\t'user-path',\n\t\t'strict',\n\t],\n\tinit: ['path', 'hook'],\n\tdoctor: [],\n\twhich: [],\n\tpin: [],\n\tinstall: [],\n\tcache: ['older-than'],\n\t'self-update': ['rollback'],\n\trecover: ['journal', 'confirm-dead-machine'],\n\tuninstall: ['yes', 'purge-cache'],\n\t'verify-attestation': ['bundle', 'tuf-cache'],\n};\n\nfunction misplacedOptions(command: string, values: Values): string[] {\n\tconst allowed = new Set<keyof Values>(COMMAND_OPTIONS[command] ?? []);\n\treturn Object.values(COMMAND_OPTIONS)\n\t\t.flat()\n\t\t.filter((option) => !allowed.has(option) && values[option] !== undefined)\n\t\t.map((option) => `--${option}`);\n}\n\nexport async function run(argv: string[], options: DispatchOptions): Promise<number> {\n\tlet parsed: ReturnType<typeof parse>;\n\ttry {\n\t\tparsed = parse(argv);\n\t} catch (error) {\n\t\tconsole.error((error as Error).message);\n\t\tconsole.error(USAGE);\n\t\treturn EXIT.usage;\n\t}\n\tconst { values, positionals } = parsed;\n\tif (values.version) {\n\t\tconsole.log(VERSION);\n\t\treturn EXIT.ok;\n\t}\n\tconst command = positionals[0];\n\tif (values.help || command === undefined) {\n\t\tconsole.log(USAGE);\n\t\treturn command === undefined && !values.help ? EXIT.usage : EXIT.ok;\n\t}\n\tif (COMMAND_OPTIONS[command] === undefined) {\n\t\tconsole.error(`Unknown command: ${command}`);\n\t\tconsole.error(USAGE);\n\t\treturn EXIT.usage;\n\t}\n\tconst misplaced = misplacedOptions(command, values);\n\tif (misplaced.length > 0) {\n\t\tconsole.error(`${misplaced.join(', ')} cannot be used with ${command}`);\n\t\treturn EXIT.usage;\n\t}\n\tconst context = createCommandContext({\n\t\t...(options.home === undefined ? {} : { home: options.home }),\n\t\t...(options.env === undefined ? {} : { env: options.env }),\n\t\t...(options.io === undefined ? {} : { io: options.io }),\n\t\tjson: values.json ?? false,\n\t\tversion: VERSION,\n\t});\n\ttry {\n\t\treturn await dispatch(command, positionals.slice(1), values, context, options);\n\t} catch (error) {\n\t\treturn reportError(error, context);\n\t}\n}\n\nasync function dispatch(\n\tcommand: string,\n\trest: string[],\n\tvalues: Values,\n\tcontext: CommandContext,\n\toptions: DispatchOptions,\n): Promise<number> {\n\tswitch (command) {\n\t\tcase 'setup': {\n\t\t\tconst shells = values.shell ?? null;\n\t\t\tconst bad = shells?.filter((shell) => !isShell(shell)) ?? [];\n\t\t\tif (bad.length > 0) {\n\t\t\t\tcontext.io.err(`--shell needs one of: ${SHELLS.join(', ')} (got ${bad.join(', ')})`);\n\t\t\t\treturn EXIT.usage;\n\t\t\t}\n\t\t\treturn setup(context, {\n\t\t\t\tlink: values.link ?? false,\n\t\t\t\tshells: shells as Shell[] | null,\n\t\t\t\tyes: values.yes ?? false,\n\t\t\t\tdryRun: values['dry-run'] ?? false,\n\t\t\t\tmodifyProfile: values['modify-profile'] ?? true,\n\t\t\t\tcmdAutorun: values['cmd-autorun'] ?? false,\n\t\t\t\tstrict: values.strict ?? false,\n\t\t\t\tuserPath: values['user-path'] ?? true,\n\t\t\t});\n\t\t}\n\t\tcase 'init': {\n\t\t\tconst shell = rest[0];\n\t\t\tif (shell === undefined || !isShell(shell)) {\n\t\t\t\tcontext.io.err(`init needs one of: ${SHELLS.join(', ')}`);\n\t\t\t\treturn EXIT.usage;\n\t\t\t}\n\t\t\tconst both = values.path !== true && values.hook !== true;\n\t\t\tprocess.stdout.write(\n\t\t\t\tprofileBlock(shell, context.dirs.home, {\n\t\t\t\t\tpath: both || values.path === true,\n\t\t\t\t\thook: both || values.hook === true,\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn EXIT.ok;\n\t\t}\n\t\tcase 'doctor':\n\t\t\treturn doctor(context);\n\t\tcase 'which': {\n\t\t\tconst result = await resolveNpm([], process.cwd(), {\n\t\t\t\thome: context.dirs.home,\n\t\t\t\t...(options.env === undefined ? {} : { env: options.env }),\n\t\t\t});\n\t\t\tcontext.io.out(context.json ? JSON.stringify(result, null, 2) : describeWhich(result));\n\t\t\treturn EXIT.ok;\n\t\t}\n\t\tcase 'pin':\n\t\t\treturn pin(context, rest[0]);\n\t\tcase 'install':\n\t\t\treturn install(context, rest[0]);\n\t\tcase 'cache': {\n\t\t\tif (rest[0] === 'list') {\n\t\t\t\treturn cacheList(context);\n\t\t\t}\n\t\t\tif (rest[0] === 'prune') {\n\t\t\t\treturn cachePrune(\n\t\t\t\t\tcontext,\n\t\t\t\t\tvalues['older-than'] === undefined ? DEFAULT_PRUNE_DAYS : Number(values['older-than']),\n\t\t\t\t);\n\t\t\t}\n\t\t\tcontext.io.err('cache needs list or prune');\n\t\t\treturn EXIT.usage;\n\t\t}\n\t\tcase 'self-update':\n\t\t\treturn selfUpdate(context, { rollback: values.rollback ?? false });\n\t\tcase 'recover': {\n\t\t\tif (values.journal === undefined || values['confirm-dead-machine'] === undefined) {\n\t\t\t\tcontext.io.err('recover needs --journal <id> and --confirm-dead-machine <machine-id>');\n\t\t\t\treturn EXIT.usage;\n\t\t\t}\n\t\t\treturn recover(context, values.journal, values['confirm-dead-machine']);\n\t\t}\n\t\tcase 'verify-attestation': {\n\t\t\t// Internal: self-update runs it in a child Node whose env carries the proxy and CA settings.\n\t\t\tif (values.bundle === undefined || values['tuf-cache'] === undefined) {\n\t\t\t\treturn EXIT.usage;\n\t\t\t}\n\t\t\tconst { verifyBundleHere } = await import('../install/provenance.ts');\n\t\t\tawait verifyBundleHere(JSON.parse(readFileSync(values.bundle, 'utf8')), values['tuf-cache']);\n\t\t\treturn EXIT.ok;\n\t\t}\n\t\tcase 'uninstall':\n\t\t\treturn uninstall(context, {\n\t\t\t\tyes: values.yes ?? false,\n\t\t\t\tpurgeCache: values['purge-cache'] ?? false,\n\t\t\t});\n\t\tdefault:\n\t\t\treturn EXIT.usage;\n\t}\n}\n\nfunction describeWhich(result: ResolveResult): string {\n\tconst where =\n\t\tresult.kind === 'own' ? \"Node's own npm\" : result.kind === 'cached' ? 'cached' : 'to download';\n\tconst from =\n\t\tresult.source === null\n\t\t\t? 'no project requirement'\n\t\t\t: `${result.source.field} in ${result.source.file}`;\n\tconst lines = [`npm ${result.version} (${where}): ${result.cliPath}`, `Source: ${from}`];\n\tif (result.warning !== null) {\n\t\tlines.push(`Warning: ${result.warning}`);\n\t}\n\treturn lines.join('\\n');\n}\n\nfunction reportError(error: unknown, context: CommandContext): number {\n\tif (isNpmVmError(error)) {\n\t\tcontext.io.err(`npm-vm: ${error.message}`);\n\t\treturn error.exitCode;\n\t}\n\tcontext.io.err(\n\t\t`npm-vm: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,\n\t);\n\treturn EXIT.problems;\n}\n\ndeclare const NPM_VM_BUILD_VERSION: string | undefined;\n\n/** The build injects the package version; running from source reads the manifest instead. */\nfunction readSelfVersion(): string {\n\tif (typeof NPM_VM_BUILD_VERSION === 'string') {\n\t\treturn NPM_VM_BUILD_VERSION;\n\t}\n\ttry {\n\t\tconst manifest = JSON.parse(\n\t\t\treadFileSync(new URL('../../package.json', import.meta.url), 'utf8'),\n\t\t) as { version?: string };\n\t\treturn manifest.version ?? '0.0.0';\n\t} catch {\n\t\treturn '0.0.0';\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAOA,MAAa,WAAW;AACxB,MAAa,gBAAgB;AAC7B,MAAa,YAAY;CAAC;CAAO;CAAO;AAAQ;AAUhD,MAAM,SAAS;;AAGf,SAAgB,eAAe,MAAoB;CAClD,MAAM,QAAQ,O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