Skip to content

A self-organizing Obsidian vault that gives AI coding agents persistent memory.

perf: find a global qmd without spawning npm root -g where npm's prefix is certain (#382)

Brenno Ferrariac5a61324aaa
diff --git a/.claude/scripts/lib/qmd.ts b/.claude/scripts/lib/qmd.ts
index d227b09..3c65caa 100644
--- a/.claude/scripts/lib/qmd.ts
+++ b/.claude/scripts/lib/qmd.ts
@@ -16,14 +16,17 @@
* this .ts helper at Node's `--experimental-strip-types` runtime. The two
* copies are asserted independently: `tests/qmd.test.ts` locks this file's
* `resolveQmdEntry` + `buildQmdCommand` shape, and `tests/qmd-mcp.test.ts`
- * locks the .mjs wrapper's equivalents. Drift between the two shows up as
- * a test failure on the CI matrix rather than a silent platform bug.
+ * locks the .mjs wrapper's equivalents; `tests/qmd.test.ts` also runs
+ * `pickQmdEntry` and `npmGlobalRoot` against both copies. Drift between the
+ * two shows up as a test failure on the CI matrix rather than a silent
+ * platform bug.
*/
import { spawn, spawnSync } from "node:child_process";
-import { existsSync } from "node:fs";
+import { existsSync, readFileSync } from "node:fs";
+import { homedir } from "node:os";
import { createRequire } from "node:module";
-import { isAbsolute, join } from "node:path";
+import { dirname, isAbsolute, join } from "node:path";
import { debug } from "./hook-io.ts";
const require = createRequire(import.meta.url);
@@ -93,7 +96,124 @@ function localQmdEntry(): string | null {
}
}
+/** What `npmGlobalRoot` reads; each defaults to this process, so tests need no real npm install. */
+export interface NpmLocation {
+ readonly env?: Readonly<Record<string, string | undefined>>;
+ readonly platform?: string;
+ readonly execPath?: string;
+ readonly home?: string;
+ /** A file's text, or null when it can't be read. */
+ readonly readText?: (path: string) => string | null;
+}
+
+function readTextOrNull(path: string): string | null {
+ try {
+ return readFileSync(path, "utf8");
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Where npm keeps global packages, without spawning it (#349): `npm root -g`
+ * is a shell plus a Node start on every resolve (0.1-1 s on CI runners,
+ * measured 2026-10-13, #349). Only the
+ * cheap exact cases are worked out here; anything else returns null, and the
+ * caller asks npm, which gives its exact answer at the old cost.
+ *
+ * 1. npm_config_prefix in the env (any case): use it if it's an absolute path
+ * with no `${`, else ask npm.
+ * 2. PREFIX, DESTDIR, npm_config_userconfig or npm_config_globalconfig set →
+ * ask npm.
+ * 3. ~/.npmrc (HOME before the OS home) or `<node prefix>/etc/npmrc` has a
+ * line setting `prefix` or `globalconfig`, sections included, or a key
+ * built from `${…}` → ask npm. An npmrc with only auth or registry lines
+ * (or `save-prefix`) doesn't count.
+ * 4. The builtin npmrc: on Windows, the installer's exact
+ * `prefix=${APPDATA}\npm` → %APPDATA%\npm. Any other line there setting
+ * `prefix`, `globalconfig` or `userconfig` (which moves the user npmrc),
+ * or a key built from `${…}` → ask npm.
+ * 5. Otherwise Node's own prefix.
+ *
+ * 4 and 5 hold only when npm sits beside this Node; where it doesn't
+ * (Homebrew, Debian's packaged npm), ask npm. Env values are read as npm
+ * reads them: trimmed, empty ones skipped, the last of several winning.
+ *
+ * Packages sit in `<prefix>\node_modules` on Windows and
+ * `<prefix>/lib/node_modules` elsewhere.
+ */
+export function npmGlobalRoot(at: NpmLocation = {}): string | null {
+ const vars = at.env ?? process.env;
+ const win = (at.platform ?? process.platform) === "win32";
+ const execPath = at.execPath ?? process.execPath;
+ const home = at.home ?? (vars["HOME"] || homedir());
+ const readText = at.readText ?? readTextOrNull;
+ // As npm's loadEnv reads it: any case, trimmed, empty skipped, the last one winning.
+ const npmConfig = (key: string): string | undefined => {
+ const want = `npm_config_${key}`;
+ let found: string | undefined;
+ for (const [name, value] of Object.entries(vars)) {
+ if (name.toLowerCase() === want && value?.trim()) found = value.trim();
+ }
+ return found;
+ };
+ const lines = (file: string): string[] =>
+ (readText(file) ?? "").split(/\r?\n/).map((l) => l.trim()).filter((l) => l !== "" && !/^[;#]/.test(l));
+ // A line setting prefix or globalconfig, sections included, or one whose
+ // key npm would expand from the environment and so can't be read here.
+ const settingLines = (file: string): string[] =>
+ lines(file).filter((l) => /^(prefix|globalconfig)\s*=/i.test(l) || /\$\{[^=]*=/.test(l));
+ // Absolute in npm's sense: on a Windows host, `\npm` is drive-relative.
+ const exactPath = (value: string): boolean =>
+ isAbsolute(value) && !value.includes("${") && (process.platform !== "win32" || !/^[\\/](?![\\/])/.test(value));
+ const layout = (prefix: string): string => (win ? join(prefix, "node_modules") : join(prefix, "lib", "node_modules"));
+
+ // 1.
+ const fromEnv = npmConfig("prefix");
+ if (fromEnv !== undefined) return exactPath(fromEnv) ? layout(fromEnv) : null;
+
+ // 2.
+ if (vars["PREFIX"] || vars["DESTDIR"] || npmConfig("userconfig") !== undefined || npmConfig("globalconfig") !== undefined) {
+ return null;
+ }
+
+ // 3.
+ const nodePrefix = win ? dirname(execPath) : dirname(dirname(execPath));
+ if (settingLines(join(home, ".npmrc")).length > 0 || settingLines(join(nodePrefix, "etc", "npmrc")).length > 0) {
+ return null;
+ }
+
+ // 4 and 5 hold only for the npm that sits beside this Node; Homebrew and
+ // Debian keep npm (and its builtin npmrc) elsewhere, so ask npm there.
+ const npmDir = join(win ? nodePrefix : join(nodePrefix, "lib"), "node_modules", "npm");
+ if (readText(join(npmDir, "package.json")) === null) return null;
+
+ // 4.
+ const builtin = lines(join(npmDir, "npmrc")).filter(
+ (l) => /^(prefix|globalconfig|userconfig)\s*=/i.test(l) || /\$\{[^=]*=/.test(l),
+ );
+ if (builtin.length === 0) return layout(nodePrefix); // 5.
+ const appdata = vars["APPDATA"];
+ if (!win || builtin.length !== 1 || builtin[0] !== "prefix=${APPDATA}\\npm" || !appdata || !exactPath(appdata)) {
+ return null;
+ }
+ // npm's global npmrc then lives under that prefix.
+ const prefix = join(appdata, "npm");
+ return settingLines(join(prefix, "etc", "npmrc")).length > 0 ? null : layout(prefix);
+}
+
+/** @tobilu/qmd's entry under a global root, when it is there. */
+function qmdEntryUnder(root: string): string | null {
+ const entry = join(root, "@tobilu", "qmd", "dist", "cli", "qmd.js");
+ return existsSync(entry) ? entry : null;
+}
+
function globalQmdEntry(): string | null {
+ // Where npm would put a global install, without spawning npm (#349).
+ const computed = npmGlobalRoot();
+ const known = computed === null ? null : qmdEntryUnder(computed);
+ if (known !== null) return known;
+
// Fallback for global npm installs that aren't on this package's resolution
// path — ask npm directly where global packages live. Bounded timeout so a
// hung npm process can't block a fire-and-forget hook indefinitely.
@@ -103,10 +223,13 @@ function globalQmdEntry(): string | null {
// shell:true (the args get concatenated into the shell command unescaped,
// a real injection risk in the general case). Our command is a literal
// constant — no user input — so the concatenated form is safe.
+ // windowsHide: under a detached, windowless parent (the bootstrap that
+ // session-start spawns), a shell started without it opens a console window.
const npmRoot = spawnSync("npm root -g", {
shell: true,
encoding: "utf8",
timeout: 3000,
+ windowsHide: true,
});
if (npmRoot.error || npmRoot.signal !== null || npmRoot.status !== 0) {
return null;
@@ -114,9 +237,7 @@ function globalQmdEntry(): string | null {
const root = (npmRoot.stdout ?? "").trim();
if (root === "" || !isAbsolute(root)) return null;
-
- const entry = join(root, "@tobilu", "qmd", "dist", "cli", "qmd.js");
- return existsSync(entry) ? entry : null;
+ return qmdEntryUnder(root);
}
/**
diff --git a/.claude/scripts/qmd-mcp.d.mts b/.claude/scripts/qmd-mcp.d.mts
index 3ec4103..5a2b6fa 100644
--- a/.claude/scripts/qmd-mcp.d.mts
+++ b/.claude/scripts/qmd-mcp.d.mts
@@ -22,6 +22,13 @@ export function pickQmdEntry(
/** Does this entrypoint start? Bounded `--version` probe. */
export function isRunnableQmdEntry(entry: string): boolean;
+/**
+ * Where npm keeps global packages, without spawning npm, in the five cheap
+ * exact cases lib/qmd.ts's npmGlobalRoot lists. Null means "ask npm", not
+ * "no global npm".
+ */
+export function npmGlobalRoot(at?: import("./lib/qmd.ts").NpmLocation): string | null;
+
/**
* Resolve the vault root directory from a `file://` URL and optional env.
* The env argument is read for `CLAUDE_PROJECT_DIR` (Claude Code's
diff --git a/.claude/scripts/qmd-mcp.mjs b/.claude/scripts/qmd-mcp.mjs
index 7d5dc9b..feadd21 100644
--- a/.claude/scripts/qmd-mcp.mjs
+++ b/.claude/scripts/qmd-mcp.mjs
@@ -126,7 +126,116 @@ function localQmdEntry() {
}
}
+function readTextOrNull(path) {
+ try {
+ return readFileSync(path, "utf8");
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The duplicate of lib/qmd.ts's npmGlobalRoot, kept in step by hand: change
+ * that one first, then carry the change here with the types removed.
+ *
+ * Where npm keeps global packages, without spawning it (#349): `npm root -g`
+ * is a shell plus a Node start on every resolve (0.1-1 s on CI runners,
+ * measured 2026-10-13, #349). Only the
+ * cheap exact cases are worked out here; anything else returns null, and the
+ * caller asks npm, which gives its exact answer at the old cost.
+ *
+ * 1. npm_config_prefix in the env (any case): use it if it's an absolute path
+ * with no `${`, else ask npm.
+ * 2. PREFIX, DESTDIR, npm_config_userconfig or npm_config_globalconfig set →
+ * ask npm.
+ * 3. ~/.npmrc (HOME before the OS home) or `<node prefix>/etc/npmrc` has a
+ * line setting `prefix` or `globalconfig`, sections included, or a key
+ * built from `${…}` → ask npm. An npmrc with only auth or registry lines
+ * (or `save-prefix`) doesn't count.
+ * 4. The builtin npmrc: on Windows, the installer's exact
+ * `prefix=${APPDATA}\npm` → %APPDATA%\npm. Any other line there setting
+ * `prefix`, `globalconfig` or `userconfig` (which moves the user npmrc),
+ * or a key built from `${…}` → ask npm.
+ * 5. Otherwise Node's own prefix.
+ *
+ * 4 and 5 hold only when npm sits beside this Node; where it doesn't
+ * (Homebrew, Debian's packaged npm), ask npm. Env values are read as npm
+ * reads them: trimmed, empty ones skipped, the last of several winning.
+ *
+ * Packages sit in `<prefix>\node_modules` on Windows and
+ * `<prefix>/lib/node_modules` elsewhere.
+ */
+export function npmGlobalRoot(at = {}) {
+ const vars = at.env ?? process.env;
+ const win = (at.platform ?? process.platform) === "win32";
+ const execPath = at.execPath ?? process.execPath;
+ const home = at.home ?? (vars["HOME"] || homedir());
+ const readText = at.readText ?? readTextOrNull;
+ // As npm's loadEnv reads it: any case, trimmed, empty skipped, the last one winning.
+ const npmConfig = (key) => {
+ const want = `npm_config_${key}`;
+ let found;
+ for (const [name, value] of Object.entries(vars)) {
+ if (name.toLowerCase() === want && value?.trim()) found = value.trim();
+ }
+ return found;
+ };
+ const lines = (file) =>
+ (readText(file) ?? "").split(/\r?\n/).map((l) => l.trim()).filter((l) => l !== "" && !/^[;#]/.test(l));
+ // A line setting prefix or globalconfig, sections included, or one whose
+ // key npm would expand from the environment and so can't be read here.
+ const settingLines = (file) =>
+ lines(file).filter((l) => /^(prefix|globalconfig)\s*=/i.test(l) || /\$\{[^=]*=/.test(l));
+ // Absolute in npm's sense: on a Windows host, `\npm` is drive-relative.
+ const exactPath = (value) =>
+ isAbsolute(value) && !value.includes("${") && (process.platform !== "win32" || !/^[\\/](?![\\/])/.test(value));
+ const layout = (prefix) => (win ? join(prefix, "node_modules") : join(prefix, "lib", "node_modules"));
+
+ // 1.
+ const fromEnv = npmConfig("prefix");
+ if (fromEnv !== undefined) return exactPath(fromEnv) ? layout(fromEnv) : null;
+
+ // 2.
+ if (vars["PREFIX"] || vars["DESTDIR"] || npmConfig("userconfig") !== undefined || npmConfig("globalconfig") !== undefined) {
+ return null;
+ }
+
+ // 3.
+ const nodePrefix = win ? dirname(execPath) : dirname(dirname(execPath));
+ if (settingLines(join(home, ".npmrc")).length > 0 || settingLines(join(nodePrefix, "etc", "npmrc")).length > 0) {
+ return null;
+ }
+
+ // 4 and 5 hold only for the npm that sits beside this Node; Homebrew and
+ // Debian keep npm (and its builtin npmrc) elsewhere, so ask npm there.
+ const npmDir = join(win ? nodePrefix : join(nodePrefix, "lib"), "node_modules", "npm");
+ if (readText(join(npmDir, "package.json")) === null) return null;
+
+ // 4.
+ const builtin = lines(join(npmDir, "npmrc")).filter(
+ (l) => /^(prefix|globalconfig|userconfig)\s*=/i.test(l) || /\$\{[^=]*=/.test(l),
+ );
+ if (builtin.length === 0) return layout(nodePrefix); // 5.
+ const appdata = vars["APPDATA"];
+ if (!win || builtin.length !== 1 || builtin[0] !== "prefix=${APPDATA}\\npm" || !appdata || !exactPath(appdata)) {
+ return null;
+ }
+ // npm's global npmrc then lives under that prefix.
+ const prefix = join(appdata, "npm");
+ return settingLines(join(prefix, "etc", "npmrc")).length > 0 ? null : layout(prefix);
+}
+
+/** @tobilu/qmd's entry under a global root, when it is there. */
+function qmdEntryUnder(root) {
+ const entry = join(root, "@tobilu", "qmd", "dist", "cli", "qmd.js");
+ return existsSync(entry) ? entry : null;
+}
+
function globalQmdEntry() {
+ // Where npm would put a global install, without spawning npm (#349).
+ const computed = npmGlobalRoot();
+ const known = computed === null ? null : qmdEntryUnder(computed);
+ if (known !== null) return known;
// Fallback for global npm installs that aren't on this package's resolution
// path — ask npm directly where global packages live. Bounded timeout so a
@@ -136,10 +245,12 @@ function globalQmdEntry() {
// stays clean on Node 24 (DEP0190 — args concatenated with shell:true is
// an injection risk in the general case; our command is a literal
// constant so the concatenated form is safe).
+ // windowsHide: under a windowless parent, a shell started without it opens a console window.
const npmRoot = spawnSync("npm root -g", {
shell: true,
encoding: "utf8",
timeout: 3000,
+ windowsHide: true,
});
if (
npmRoot.error ||
@@ -156,9 +267,7 @@ function globalQmdEntry() {
if (root === "" || !isAbsolute(root)) {
return null;
}
-
- const entry = join(root, "@tobilu", "qmd", "dist", "cli", "qmd.js");
- return existsSync(entry) ? entry : null;
+ return qmdEntryUnder(root);
}
/**
diff --git a/.claude/scripts/tests/qmd.test.ts b/.claude/scripts/tests/qmd.test.ts
index c9e2b86..53f52f6 100644
--- a/.claude/scripts/tests/qmd.test.ts
+++ b/.claude/scripts/tests/qmd.test.ts
@@ -9,13 +9,15 @@
import { test, describe } from "node:test";
import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { isAbsolute, join } from "node:path";
+import { isAbsolute, join, resolve } from "node:path";
import {
buildQmdCommand,
isRunnableQmdEntry,
+ npmGlobalRoot as npmGlobalRootTs,
parseVersionTriple,
pickQmdEntry,
qmdVersionAtLeast,
@@ -23,6 +25,7 @@ import {
} from "../lib/qmd.ts";
import {
isRunnableQmdEntry as isRunnableQmdEntryMjs,
+ npmGlobalRoot as npmGlobalRootMjs,
pickQmdEntry as pickQmdEntryMjs,
} from "../qmd-mcp.mjs";
@@ -213,3 +216,165 @@ describe("qmdVersionAtLeast", () => {
assert.equal(qmdVersionAtLeast("2.5.3", "latest"), true);
});
});
+
+// Where npm keeps global packages, without spawning npm (#349): only the
+// cheap exact cases npmGlobalRoot's doc lists, and null (ask npm) for the
+// rest. Both copies of the resolver run the same cases; the last checks the
+// real npm on this machine.
+
+/** The real npm's answer on this machine, asked at most once for both copies; null without npm. */
+let npmAsked: string | null | undefined;
+const npmAnswer = (): string | null => {
+ if (npmAsked === undefined) {
+ const npm = spawnSync("npm root -g", { shell: true, encoding: "utf8", timeout: 15_000 });
+ const asked = (npm.stdout ?? "").trim();
+ npmAsked = npm.status === 0 && asked !== "" ? asked : null;
+ }
+ return npmAsked;
+};
+
+for (const [label, npmGlobalRoot] of [
+ ["lib/qmd.ts", npmGlobalRootTs],
+ ["qmd-mcp.mjs", npmGlobalRootMjs],
+] as const) {
+ describe(`${label} npmGlobalRoot`, () => {
+ const home = join(tmpdir(), "home");
+ const nodeDir = join(tmpdir(), "nodejs");
+ const winNpm = join(nodeDir, "node_modules", "npm");
+ const posixNpm = join(nodeDir, "lib", "node_modules", "npm");
+ // npm sits beside this Node unless a test says otherwise.
+ const npmBeside = { [join(winNpm, "package.json")]: "{}", [join(posixNpm, "package.json")]: "{}" };
+ const files = (map: Record<string, string>) => (path: string) => ({ ...npmBeside, ...map })[path] ?? null;
+ const win = (env: Record<string, string> = {}, text: Record<string, string> = {}) =>
+ npmGlobalRoot({ env, platform: "win32", execPath: join(nodeDir, "node.exe"), home, readText: files(text) });
+ const posix = (env: Record<string, string> = {}, text: Record<string, string> = {}) =>
+ npmGlobalRoot({ env, platform: "linux", execPath: join(nodeDir, "bin", "node"), home, readText: files(text) });
+ const winBuiltin = join(winNpm, "npmrc");
+ const posixBuiltin = join(posixNpm, "npmrc");
+ const userNpmrc = join(home, ".npmrc");
+
+ test("5: nothing configured is Node's own prefix, laid out per platform", () => {
+ assert.equal(win(), join(nodeDir, "node_modules"));
+ assert.equal(posix(), join(nodeDir, "lib", "node_modules"));
+ });
+
+ test("1: npm_config_prefix in the env, in any case, beats every npmrc", () => {
+ const p = join(tmpdir(), "env-prefix");
+ const npmrc = { [userNpmrc]: "prefix=/elsewhere" };
+ assert.equal(win({ npm_config_prefix: p }, npmrc), join(p, "node_modules"));
+ assert.equal(posix({ NPM_CONFIG_PREFIX: p }, npmrc), join(p, "lib", "node_modules"));
+ assert.equal(posix({ Npm_Config_Prefix: p }), join(p, "lib", "node_modules"));
+ });
+
+ test("1: an env prefix that isn't absolute, or holds ${, asks npm", () => {
+ assert.equal(posix({ npm_config_prefix: "relative/dir" }), null);
+ assert.equal(posix({ npm_config_prefix: join(tmpdir(), "${NAME}") }), null);
+ });
+
+ test("1: env values are read as npm reads them: trimmed, empty skipped, the last winning", () => {
+ const a = join(tmpdir(), "a");
+ const b = join(tmpdir(), "b");
+ assert.equal(posix({ npm_config_prefix: `${a} ` }), join(a, "lib", "node_modules"));
+ assert.equal(posix({ npm_config_prefix: "" }), join(nodeDir, "lib", "node_modules"), "empty is unset");
+ assert.equal(posix({ npm_config_prefix: a, NPM_CONFIG_PREFIX: b }), join(b, "lib", "node_modules"));
+ });
+
+ test("1: on a Windows host, a drive-relative prefix asks npm", { skip: process.platform !== "win32" }, () => {
+ assert.equal(win({ npm_config_prefix: "\\npm" }), null);
+ assert.equal(win({ npm_config_prefix: "/npm" }), null);
+ });
+
+ test("2: PREFIX, DESTDIR, npm_config_userconfig or npm_config_globalconfig set asks npm", () => {
+ for (const key of ["PREFIX", "DESTDIR", "npm_config_userconfig", "NPM_CONFIG_GLOBALCONFIG"]) {
+ assert.equal(posix({ [key]: join(tmpdir(), "x") }), null, key);
+ }
+ });
+
+ test("3: a user or global npmrc that mentions prefix or globalconfig, sections included, asks npm", () => {
+ assert.equal(posix({}, { [userNpmrc]: "prefix=/opt/npm" }), null);
+ assert.equal(posix({}, { [userNpmrc]: "[project]\nprefix = /opt/npm" }), null);
+ assert.equal(posix({}, { [userNpmrc]: `globalconfig=${join(tmpdir(), "g")}` }), null);
+ assert.equal(posix({}, { [join(nodeDir, "etc", "npmrc")]: "prefix=/opt/npm" }), null);
+ assert.equal(win({}, { [join(nodeDir, "etc", "npmrc")]: "prefix=C:\\npm" }), null);
+ });
+
+ test("3: an npmrc with only auth, registry or save-prefix lines doesn't count", () => {
+ const auth = {
+ [userNpmrc]:
+ "registry=https://registry.example.com/\n//registry.example.com/:_authToken=abc\nsave-prefix=~\n; prefix=/commented\n# ${NPMKEY}=/commented\n",
+ };
+ assert.equal(posix({}, auth), join(nodeDir, "lib", "node_modules"));
+ });
+
+ test("3: a key npm would build from ${...} asks npm", () => {
+ assert.equal(posix({}, { [userNpmrc]: "${NPMKEY}=/opt/g" }), null);
+ });
+
+ test("3: HOME is read before the OS home", () => {
+ const h = join(tmpdir(), "h");
+ const at = (text: Record<string, string>) =>
+ npmGlobalRoot({ env: { HOME: h }, platform: "linux", execPath: join(nodeDir, "bin", "node"), readText: files(text) });
+ assert.equal(at({ [join(h, ".npmrc")]: "prefix=/opt/npm" }), null);
+ assert.equal(at({}), join(nodeDir, "lib", "node_modules"));
+ });
+
+ test("4: the Windows installer's builtin npmrc is %APPDATA%\\npm, comments and blank lines aside", () => {
+ const appdata = join(tmpdir(), "Roaming");
+ assert.equal(
+ win({ APPDATA: appdata }, { [winBuiltin]: "; installer default\n\nprefix=${APPDATA}\\npm\n" }),
+ join(appdata, "npm", "node_modules"),
+ );
+ });
+
+ test("4: anything else in the builtin npmrc asks npm", () => {
+ const appdata = join(tmpdir(), "Roaming");
+ assert.equal(win({ APPDATA: appdata }, { [winBuiltin]: "prefix=C:\\npm\\prefix" }), null);
+ assert.equal(win({}, { [winBuiltin]: "prefix=${APPDATA}\\npm" }), null, "no APPDATA to expand");
+ assert.equal(
+ win({ APPDATA: appdata }, { [winBuiltin]: "prefix=${APPDATA}\\npm\nuserconfig=D:\\cfg\\npmrc" }),
+ null,
+ "another setting beside the installer's line",
+ );
+ assert.equal(posix({}, { [posixBuiltin]: "prefix=/opt/homebrew" }), null);
+ assert.equal(posix({}, { [posixBuiltin]: "userconfig=/etc/other-npmrc" }), null, "it moves the user npmrc");
+ });
+
+ test("4: other keys in the builtin npmrc don't count", () => {
+ assert.equal(posix({}, { [posixBuiltin]: "update-notifier=false\n" }), join(nodeDir, "lib", "node_modules"));
+ const appdata = join(tmpdir(), "Roaming");
+ assert.equal(
+ win({ APPDATA: appdata }, { [winBuiltin]: "update-notifier=false\nprefix=${APPDATA}\\npm" }),
+ join(appdata, "npm", "node_modules"),
+ );
+ });
+
+ test("4 and 5: with no npm beside this Node (Homebrew, Debian), ask npm", () => {
+ const noNpm = () => null;
+ assert.equal(npmGlobalRoot({ env: {}, platform: "linux", execPath: join(nodeDir, "bin", "node"), home, readText: noNpm }), null);
+ assert.equal(npmGlobalRoot({ env: {}, platform: "win32", execPath: join(nodeDir, "node.exe"), home, readText: noNpm }), null);
+ });
+
+ test("4: the global npmrc under %APPDATA%\\npm still counts", () => {
+ const appdata = join(tmpdir(), "Roaming");
+ assert.equal(
+ win(
+ { APPDATA: appdata },
+ { [winBuiltin]: "prefix=${APPDATA}\\npm", [join(appdata, "npm", "etc", "npmrc")]: "prefix=D:\\npm" },
+ ),
+ null,
+ );
+ });
+
+ // The property that matters: a root worked out here that holds qmd is
+ // the root npm would give. A null only costs the spawn it would save.
+ test("where it finds qmd on this machine, npm agrees", (t) => {
+ const ours = npmGlobalRoot();
+ if (ours === null || !existsSync(join(ours, "@tobilu", "qmd", "dist", "cli", "qmd.js"))) {
+ return t.skip("no qmd under a worked-out root here; the caller asks npm");
+ }
+ const answer = npmAnswer();
+ if (answer === null) return t.skip("npm is not available here");
+ assert.equal(resolve(ours).toLowerCase(), resolve(answer).toLowerCase());
+ });
+ });
+}