Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 50 additions & 22 deletions .claude/scripts/lib/qmd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
* 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; `tests/qmd.test.ts` also runs
* `pickQmdEntry` and `npmGlobalRoot` against both copies. Drift between the
* `pickQmdEntry`, `npmGlobalRoot` and `globalQmdEntry` against both copies. Drift between the
* two shows up as a test failure on the CI matrix rather than a silent
* platform bug.
*/
Expand Down Expand Up @@ -102,6 +102,8 @@ export interface NpmLocation {
readonly platform?: string;
readonly execPath?: string;
readonly home?: string;
/** The OS home lookup; it throws for a UID with no passwd entry. */
readonly osHome?: () => string;
/** A file's text, or null when it can't be read. */
readonly readText?: (path: string) => string | null;
}
Expand All @@ -122,22 +124,26 @@ function readTextOrNull(path: string): string | null {
* 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.
* with no `${` and no surrounding whitespace, 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.
* npm's ini would rewrite (quoted, which it unquotes, escapes and all;
* built from `${…}`; or holding `;` or `#`, which cut it, brackets, a
* backslash or whitespace) → 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.
* or a key npm's ini would rewrite → 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.
* reads them: only "" skipped, nothing trimmed, the last of several winning
* (@npmcli/config's loadEnv, read in npm 10.9.2 on 2026-10-14). Rule 3 needs a home: when
* the OS can't name one (a UID with no passwd entry), ask npm.
*
* Packages sit in `<prefix>\node_modules` on Windows and
* `<prefix>/lib/node_modules` elsewhere.
Expand All @@ -146,26 +152,36 @@ 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.
// Rule 1's env reading: the last non-empty value, untrimmed.
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();
if (name.toLowerCase() === want && value) found = value;
}
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));
// Rules 3 and 4: a line setting one of `keys`, or one whose key npm's
// ini would turn into something this can't read: quoted (unquoted and
// decoded), built from `${…}`, or holding `;` or `#` (ini cuts the key
// there), brackets, a backslash or whitespace. Auth keys (`//host/path/:_authToken`, with % ~ +) are
// plain. Section headers set nothing.
const settingLines = (file: string, keys: readonly string[] = ["prefix", "globalconfig"]): string[] =>
lines(file).filter((l) => {
if (l.startsWith("[")) return false;
const key = l.split("=", 1)[0]!.trim();
return keys.includes(key.toLowerCase()) || /^["']|\$\{|[\s[\]\\;#]/.test(key);
});
// Absolute in npm's sense: on a Windows host, `\npm` is drive-relative.
// Padded values ask npm: how its path handling treats them is not read here.
const exactPath = (value: string): boolean =>
isAbsolute(value) && !value.includes("${") && (process.platform !== "win32" || !/^[\\/](?![\\/])/.test(value));
value === value.trim() &&
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.
Expand All @@ -178,6 +194,12 @@ export function npmGlobalRoot(at: NpmLocation = {}): string | null {
}

// 3.
let home: string;
try {
home = at.home ?? (vars["HOME"] || (at.osHome ?? homedir)());
} catch {
return null; // no home to find ~/.npmrc in (a UID with no passwd entry)
}
const nodePrefix = win ? dirname(execPath) : dirname(dirname(execPath));
if (settingLines(join(home, ".npmrc")).length > 0 || settingLines(join(nodePrefix, "etc", "npmrc")).length > 0) {
return null;
Expand All @@ -189,9 +211,7 @@ export function npmGlobalRoot(at: NpmLocation = {}): string | null {
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),
);
const builtin = settingLines(join(npmDir, "npmrc"), ["prefix", "globalconfig", "userconfig"]);
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)) {
Expand All @@ -208,12 +228,21 @@ function qmdEntryUnder(root: string): string | null {
return existsSync(entry) ? entry : null;
}

function globalQmdEntry(): string | null {
// Where npm would put a global install, without spawning npm (#349).
const computed = npmGlobalRoot();
/**
* qmd's entry under npm's global root: under the root `npmGlobalRoot` works
* out when qmd is there, else under npm's own answer. A worked-out root
* models the npm beside this Node, and the npm on PATH can differ (a
* self-upgraded npm on Windows, mixed installs; inferred), so a miss there
* still asks npm (#399, 2026-10-14).
*/
export function globalQmdEntry(computed: string | null = npmGlobalRoot(), askNpm: () => string | null = askNpmForRoot): string | null {
const known = computed === null ? null : qmdEntryUnder(computed);
if (known !== null) return known;
const root = askNpm();
return root === null ? null : qmdEntryUnder(root);
}

function askNpmForRoot(): string | null {
// 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.
Expand All @@ -236,8 +265,7 @@ function globalQmdEntry(): string | null {
}

const root = (npmRoot.stdout ?? "").trim();
if (root === "" || !isAbsolute(root)) return null;
return qmdEntryUnder(root);
return root === "" || !isAbsolute(root) ? null : root;
}

/**
Expand Down
2 changes: 2 additions & 0 deletions .claude/scripts/qmd-mcp.d.mts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ export function isRunnableQmdEntry(entry: string): boolean;
* "no global npm".
*/
export function npmGlobalRoot(at?: import("./lib/qmd.ts").NpmLocation): string | null;
/** qmd's entry under npm's global root: a worked-out root is the answer; npm is asked only without one. */
export function globalQmdEntry(computed?: string | null, askNpm?: () => string | null): string | null;

/**
* Resolve the vault root directory from a `file://` URL and optional env.
Expand Down
75 changes: 50 additions & 25 deletions .claude/scripts/qmd-mcp.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,8 @@ function readTextOrNull(path) {
}

/**
* The duplicate of lib/qmd.ts's npmGlobalRoot, kept in step by hand: change
* The duplicate of lib/qmd.ts's npmGlobalRoot (and, below, globalQmdEntry and
* askNpmForRoot), 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`
Expand All @@ -145,22 +146,26 @@ function readTextOrNull(path) {
* 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.
* with no `${` and no surrounding whitespace, 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.
* npm's ini would rewrite (quoted, which it unquotes, escapes and all;
* built from `${…}`; or holding `;` or `#`, which cut it, brackets, a
* backslash or whitespace) → 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.
* or a key npm's ini would rewrite → 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.
* reads them: only "" skipped, nothing trimmed, the last of several winning
* (@npmcli/config's loadEnv, read in npm 10.9.2 on 2026-10-14). Rule 3 needs a home: when
* the OS can't name one (a UID with no passwd entry), ask npm.
*
* Packages sit in `<prefix>\node_modules` on Windows and
* `<prefix>/lib/node_modules` elsewhere.
Expand All @@ -169,26 +174,36 @@ 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.
// Rule 1's env reading: the last non-empty value, untrimmed.
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();
if (name.toLowerCase() === want && value) found = value;
}
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));
// Rules 3 and 4: a line setting one of `keys`, or one whose key npm's
// ini would turn into something this can't read: quoted (unquoted and
// decoded), built from `${…}`, or holding `;` or `#` (ini cuts the key
// there), brackets, a backslash or whitespace. Auth keys (`//host/path/:_authToken`, with % ~ +) are
// plain. Section headers set nothing.
const settingLines = (file, keys = ["prefix", "globalconfig"]) =>
lines(file).filter((l) => {
if (l.startsWith("[")) return false;
const key = l.split("=", 1)[0].trim();
return keys.includes(key.toLowerCase()) || /^["']|\$\{|[\s[\]\\;#]/.test(key);
});
// Absolute in npm's sense: on a Windows host, `\npm` is drive-relative.
// Padded values ask npm: how its path handling treats them is not read here.
const exactPath = (value) =>
isAbsolute(value) && !value.includes("${") && (process.platform !== "win32" || !/^[\\/](?![\\/])/.test(value));
value === value.trim() &&
isAbsolute(value) &&
!value.includes("${") &&
(process.platform !== "win32" || !/^[\\/](?![\\/])/.test(value));
const layout = (prefix) => (win ? join(prefix, "node_modules") : join(prefix, "lib", "node_modules"));

// 1.
Expand All @@ -201,6 +216,12 @@ export function npmGlobalRoot(at = {}) {
}

// 3.
let home;
try {
home = at.home ?? (vars["HOME"] || (at.osHome ?? homedir)());
} catch {
return null; // no home to find ~/.npmrc in (a UID with no passwd entry)
}
const nodePrefix = win ? dirname(execPath) : dirname(dirname(execPath));
if (settingLines(join(home, ".npmrc")).length > 0 || settingLines(join(nodePrefix, "etc", "npmrc")).length > 0) {
return null;
Expand All @@ -212,9 +233,7 @@ export function npmGlobalRoot(at = {}) {
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),
);
const builtin = settingLines(join(npmDir, "npmrc"), ["prefix", "globalconfig", "userconfig"]);
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)) {
Expand All @@ -231,12 +250,21 @@ function qmdEntryUnder(root) {
return existsSync(entry) ? entry : null;
}

function globalQmdEntry() {
// Where npm would put a global install, without spawning npm (#349).
const computed = npmGlobalRoot();
/**
* qmd's entry under npm's global root: under the root `npmGlobalRoot` works
* out when qmd is there, else under npm's own answer. A worked-out root
* models the npm beside this Node, and the npm on PATH can differ (a
* self-upgraded npm on Windows, mixed installs; inferred), so a miss there
* still asks npm (#399, 2026-10-14).
*/
export function globalQmdEntry(computed = npmGlobalRoot(), askNpm = askNpmForRoot) {
const known = computed === null ? null : qmdEntryUnder(computed);
if (known !== null) return known;
const root = askNpm();
return root === null ? null : qmdEntryUnder(root);
}

function askNpmForRoot() {
// 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 MCP server startup indefinitely.
Expand All @@ -263,11 +291,8 @@ function globalQmdEntry() {
// Guard against success-with-empty-stdout or a relative path — either would
// make join() produce a path anchored at cwd, and existsSync could then
// match a local folder by accident.
const root = npmRoot.stdout.trim();
if (root === "" || !isAbsolute(root)) {
return null;
}
return qmdEntryUnder(root);
const root = (npmRoot.stdout ?? "").trim();
return root === "" || !isAbsolute(root) ? null : root;
}

/**
Expand Down
Loading
Loading