fix(editor): navigate package.json dependencies to the installed package (#7800)

Go to Declaration / Cmd-click on a dependency entry of package.json had nothing to answer it. The reference fallback now resolves dependency entries of dependencies, devDependencies, peerDependencies and optionalDependencies: a name opens the installed package's package.json, a version reveals the package folder in the Project view, and an uninstalled package reports a missing reference. node_modules is looked up from the manifest upwards (hoisted installs, scoped packages); alias, workspace, path and URL ranges are skipped.

Closes #7665
Closes #7734

Co-authored-by: Inf1mum <[email protected]>
Цей коміт міститься в:
Vadim LazukтаInf1mum authored and GitHub committed 2026-12-03 21:17:00 +08:00
1 джерело 3f7a072fa1
коміт 856fc3009e
4 files changed
+446 -3

No files matched your search

+86 -3
Переглянути файл
@@ -1,12 +1,60 @@
import { describe, expect, it } from "vitest";
import { Text } from "@codemirror/state";
import { fragmentOffset, linkReference, looksLikePath, resolvePath, textReference } from "./links";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState, Text } from "@codemirror/state";
import type { commands } from "@/platform/ipc";
const isTauri = vi.hoisted(() => vi.fn(() => true));
const fsEntryKind = vi.hoisted(() => vi.fn<typeof commands.fsEntryKind>());
const fsProbe = vi.hoisted(() => vi.fn<typeof commands.fsProbe>());
const fsResolveReference = vi.hoisted(() => vi.fn<typeof commands.fsResolveReference>());
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return {
...real,
isTauri,
commands: {
...real.commands,
fsEntryKind,
fsProbe,
fsResolveReference,
lspDocumentLinks: vi.fn(async () => ({ status: "ok", data: [] })),
},
};
});
const { fragmentOffset, linkReference, looksLikePath, referenceAt, resolvePath, textReference } =
await import("./links");
const at = (src: string, marker = "|") => {
const offset = src.indexOf(marker);
return { text: Text.of(src.replace(marker, "").split("\n")), offset };
};
/** Directs `fsEntryKind` at a set of existing dirs and files. */
const fileSystem = (dirs: string[], files: string[]) => {
fsEntryKind.mockImplementation(async (path: string) => {
if (dirs.includes(path)) return { status: "ok", data: "dir" as const };
if (files.includes(path)) return { status: "ok", data: "file" as const };
return { status: "error", error: { kind: "notFound" as const, message: `no ${path}` } };
});
fsProbe.mockImplementation(async (path: string) => {
if (files.includes(path)) return { status: "ok", data: { size: 1, binary: false, tooLarge: false } };
return { status: "error", error: { kind: "notFound" as const, message: `no ${path}` } };
});
};
const referenceInView = async (source: string, marker = "|", path = "/w/package.json") => {
const { text, offset } = at(source, marker);
const view = { state: EditorState.create({ doc: text }) } as unknown as Parameters<typeof referenceAt>[0];
return referenceAt(view, { doc: 1, path, language: "json", uiMode: null, readOnly: false }, offset);
};
beforeEach(() => {
isTauri.mockReturnValue(true);
fsEntryKind.mockReset();
fsProbe.mockReset();
fsResolveReference.mockReset();
});
describe("text references", () => {
it("finds URLs, trimming trailing punctuation", () => {
const { text, offset } = at("// see https://exa|mple.com/a?b=1.");
@@ -107,3 +155,38 @@ describe("links and fragments", () => {
expect(fragmentOffset("x", "/i.html", "nope")).toBeNull();
});
});
describe("package.json dependencies", () => {
it("navigates a dependency name to the installed package's package.json", async () => {
fileSystem(["/w/node_modules/react"], ["/w/node_modules/react/package.json"]);
await expect(referenceInView('{\n "dependencies": {\n "re|act": "^18.2.0"\n }\n}')).resolves.toMatchObject({
kind: "file",
path: "/w/node_modules/react/package.json",
});
});
it("navigates a dependency version to the installed package folder", async () => {
fileSystem(["/w/node_modules/react"], ["/w/node_modules/react/package.json"]);
await expect(referenceInView('{\n "dependencies": {\n "react": "^18.|2.0"\n }\n}')).resolves.toMatchObject({
kind: "folder",
path: "/w/node_modules/react",
});
});
it("reports a dependency that is not installed", async () => {
fileSystem([], []);
await expect(referenceInView('{\n "dependencies": {\n "re|act": "^18.2.0"\n }\n}')).resolves.toMatchObject({
kind: "missing",
value: "react",
});
});
it("still resolves plain file paths in a manifest", async () => {
fileSystem([], ["/w/lib/index.js"]);
fsResolveReference.mockResolvedValue({ status: "ok", data: "/w/lib/index.js" });
await expect(referenceInView('{\n "main": "./lib/in|dex.js"\n}')).resolves.toMatchObject({
kind: "file",
path: "/w/lib/index.js",
});
});
});
+7
Переглянути файл
@@ -15,6 +15,7 @@ import { openExternalUrl } from "@/platform/openUrl";
import { executeAction } from "@/platform/actions";
import { editorService } from "@/workbench/contributions";
import { lspRequest } from "./lsp";
import { npmDependencyReference } from "./npmDependencies";
import { rangeToOffsets } from "./positions";
export type Reference =
@@ -207,6 +208,12 @@ export async function referenceAt(view: EditorView, doc: EditorDocContext, offse
const ref = textReference(view.state.doc, offset);
if (link?.kind !== "file") {
if (link) return link;
// A dependency entry in `package.json` names its installed package — a name or a
// version, which the generic quoted-path guess below cannot resolve (#7665, #7734).
if (!doc.virtual) {
const npm = await npmDependencyReference(view.state.doc, offset, doc.path);
if (npm) return npm;
}
if (!ref || doc.virtual) return ref?.kind === "url" ? ref : null;
return resolvePath(ref, doc.path);
}
+176
Переглянути файл
@@ -0,0 +1,176 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { Text } from "@codemirror/state";
import type { commands } from "@/platform/ipc";
const isTauri = vi.hoisted(() => vi.fn(() => true));
const fsEntryKind = vi.hoisted(() => vi.fn<typeof commands.fsEntryKind>());
const fsProbe = vi.hoisted(() => vi.fn<typeof commands.fsProbe>());
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return {
...real,
isTauri,
commands: {
...real.commands,
fsEntryKind,
fsProbe,
},
};
});
const { npmDependencyAt, npmDependencyReference } = await import("./npmDependencies");
const at = (src: string, marker = "|") => {
const offset = src.indexOf(marker);
return { text: Text.of(src.replace(marker, "").split("\n")), offset };
};
/** Directs `fsEntryKind` at a set of existing dirs and files. */
const fileSystem = (dirs: string[], files: string[]) => {
fsEntryKind.mockImplementation(async (path: string) => {
if (dirs.includes(path)) return { status: "ok", data: "dir" as const };
if (files.includes(path)) return { status: "ok", data: "file" as const };
return { status: "error", error: { kind: "notFound" as const, message: `no ${path}` } };
});
fsProbe.mockImplementation(async (path: string) => {
if (files.includes(path)) return { status: "ok", data: { size: 1, binary: false, tooLarge: false } };
return { status: "error", error: { kind: "notFound" as const, message: `no ${path}` } };
});
};
beforeEach(() => {
isTauri.mockReturnValue(true);
fsEntryKind.mockReset();
fsProbe.mockReset();
});
describe("npm dependency detection", () => {
it("finds the dependency name and its exact string bounds", () => {
const source = `{\n "dependencies": {\n "reac|t": "^18.2.0"\n }\n}`;
const { text, offset } = at(source);
const from = source.replace("|", "").indexOf('"react"') + 1;
expect(npmDependencyAt(text, offset)).toEqual({ package: "react", part: "name", from, to: from + 5 });
expect(npmDependencyAt(text, from)).toMatchObject({ package: "react", part: "name" });
expect(npmDependencyAt(text, from + 5)).toMatchObject({ package: "react", part: "name" });
expect(npmDependencyAt(text, from - 1)).toBeNull();
});
it("finds the version string", () => {
const source = `{\n "dependencies": {\n "react": "^18.|2.0"\n }\n}`;
const { text, offset } = at(source);
const from = source.replace("|", "").indexOf('"^18.2.0"') + 1;
expect(npmDependencyAt(text, offset)).toEqual({ package: "react", part: "version", from, to: from + 7 });
});
it("finds scoped packages, name and version", () => {
const source = `{\n "dependencies": {\n "@types/no|de": "^20.11.0"\n }\n}`;
const { text, offset } = at(source);
expect(npmDependencyAt(text, offset)).toMatchObject({ package: "@types/node", part: "name" });
const version = at(`{\n "dependencies": {\n "@types/node": "^20.|11.0"\n }\n}`);
expect(npmDependencyAt(version.text, version.offset)).toMatchObject({
package: "@types/node",
part: "version",
});
});
it("finds dependencies in all four sections, top-level only", () => {
for (const section of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
const { text, offset } = at(`{\n "${section}": {\n "re|act": "^18.2.0"\n }\n}`);
expect(npmDependencyAt(text, offset)).toMatchObject({ package: "react", part: "name" });
}
// The same key nested one level deeper is not a dependency section.
const nested = at(`{\n "overrides": {\n "re|act": "^18.2.0"\n }\n}`);
expect(npmDependencyAt(nested.text, nested.offset)).toBeNull();
const deep = at(`{\n "scripts": {\n "dependencies": {\n "re|act": "^1"\n }\n }\n}`);
expect(npmDependencyAt(deep.text, deep.offset)).toBeNull();
});
it("ignores non-dependency strings: other keys, arrays, invalid package names", () => {
for (const source of [
'{\n "na|me": "app"\n}',
'{\n "dependencies": ["rea|ct"]\n}',
'{\n "dependencies": {\n "Rea|ct": "^18.2.0"\n }\n}',
'{\n "dependencies": {\n "./lo|cal": "file:."\n }\n}',
'{\n "dependencies": {\n "_pri|vate": "^1"\n }\n}',
]) {
const { text, offset } = at(source);
expect(npmDependencyAt(text, offset)).toBeNull();
}
});
it("ignores alias, workspace and URL version protocols", () => {
for (const version of ["npm:react@^18", "workspace:*", "github:user/repo", "git+https://x/y.git"]) {
const source = `{\n "dependencies": {\n "react": "${version.slice(0, 6)}|${version.slice(6)}"\n }\n}`;
const { text, offset } = at(source);
expect(npmDependencyAt(text, offset)).toBeNull();
}
});
it("matches a version while it is being typed (unclosed string)", () => {
const { text, offset } = at(`{\n "dependencies": {\n "react": "^18.|\n }\n}`);
expect(npmDependencyAt(text, offset)).toMatchObject({ package: "react", part: "version" });
});
});
describe("npm dependency references", () => {
it("opens the installed package's package.json from the dependency name", async () => {
fileSystem(["/w/node_modules/react"], ["/w/node_modules/react/package.json"]);
const ref = await npmDependencyReference(
...(Object.values(at(`{\n "dependencies": {\n "re|act": "^18.2.0"\n }\n}`)) as [Text, number]),
"/w/package.json",
);
expect(ref).toEqual({
kind: "file",
from: expect.any(Number),
to: expect.any(Number),
path: "/w/node_modules/react/package.json",
});
});
it("reveals the installed package folder from the version string", async () => {
fileSystem(["/w/node_modules/react"], ["/w/node_modules/react/package.json"]);
const ref = await npmDependencyReference(
...(Object.values(at(`{\n "dependencies": {\n "react": "^18.|2.0"\n }\n}`)) as [Text, number]),
"/w/package.json",
);
expect(ref).toMatchObject({ kind: "folder", path: "/w/node_modules/react" });
});
it("resolves scoped packages", async () => {
fileSystem(["/w/node_modules/@types/node"], ["/w/node_modules/@types/node/package.json"]);
const { text, offset } = at(`{\n "dependencies": {\n "@types/no|de": "^20.11.0"\n }\n}`);
expect(await npmDependencyReference(text, offset, "/w/package.json")).toMatchObject({
kind: "file",
path: "/w/node_modules/@types/node/package.json",
});
});
it("walks up to hoisted node_modules above the manifest", async () => {
fileSystem(["/w/node_modules/react"], ["/w/node_modules/react/package.json"]);
const { text, offset } = at(`{\n "dependencies": {\n "re|act": "^18.2.0"\n }\n}`);
expect(await npmDependencyReference(text, offset, "/w/a/b/package.json")).toMatchObject({
kind: "file",
path: "/w/node_modules/react/package.json",
});
});
it("reports a dependency that is not installed", async () => {
fileSystem([], []);
const { text, offset } = at(`{\n "dependencies": {\n "re|act": "^18.2.0"\n }\n}`);
expect(await npmDependencyReference(text, offset, "/w/package.json")).toMatchObject({
kind: "missing",
value: "react",
});
});
it("answers nothing outside a manifest, offline, or off a dependency entry", async () => {
fileSystem(["/w/node_modules/react"], ["/w/node_modules/react/package.json"]);
const { text, offset } = at(`{\n "dependencies": {\n "re|act": "^18.2.0"\n }\n}`);
expect(await npmDependencyReference(text, offset, "/w/notes.md")).toBeNull();
isTauri.mockReturnValue(false);
expect(await npmDependencyReference(text, offset, "/w/package.json")).toBeNull();
isTauri.mockReturnValue(true);
const other = at(`{\n "scripts": {\n "test": "vi|test"\n }\n}`);
expect(await npmDependencyReference(other.text, other.offset, "/w/package.json")).toBeNull();
});
});
+177
Переглянути файл
@@ -0,0 +1,177 @@
/**
* Dependency entries in a `package.json` as references for Go to Declaration and ⌘-click,
* where no language server answers a manifest: a dependency name opens the installed
* package's `package.json`, its version string reveals the installed package folder in the
* project view (#7665, #7734). The package is looked up under `node_modules` at or above
* the manifest (hoisted monorepo installs). Entries are recognized with the same top-level
* sections and name rules as the backend's `npm::dependency_at` (version completion), so
* navigation and completion never disagree about what a dependency entry is.
*/
import type { Text } from "@codemirror/state";
import { call, commands, isTauri } from "@/platform/ipc";
import type { Reference } from "./links";
const MANIFEST = /(?:^|\/)package\.json$/i;
/** Top-level objects whose string values are version ranges, as in the backend. */
const SECTIONS: ReadonlySet<string> = new Set([
"dependencies",
"devDependencies",
"peerDependencies",
"optionalDependencies",
]);
export interface NpmDependency {
package: string;
/** Which string the offset is on: the entry key (the name) or its value (the range). */
part: "name" | "version";
/** The string's content bounds (inside the quotes), as in `ManifestDependency`. */
from: number;
to: number;
}
const namePart = (part: string) =>
part.length > 0 && !part.startsWith(".") && !part.startsWith("_") && /^[a-z0-9._~-]*$/.test(part);
/** npm package names: lowercase, optionally scoped (`@scope/name`), as in the backend. */
const isPackageName = (name: string): boolean => {
if (name.length > 214) return false;
if (!name.startsWith("@")) return namePart(name);
const slash = name.indexOf("/");
return slash > 0 && namePart(name.slice(1, slash)) && namePart(name.slice(slash + 1));
};
/** Alias (`npm:x`), workspace, path and URL ranges are not versions to navigate. */
const isVersionRange = (value: string): boolean => !/[:/]/.test(value);
interface Frame {
object: boolean;
/** The last key read in this object, awaiting its value. */
pendingKey: string | null;
/** A `:` followed: the next string is a value, not a key. */
expectingValue: boolean;
/** The key whose value this container is (`dependencies` for a section object). */
owner: string | null;
}
/**
* The dependency entry at a UTF-16 `offset`, also in a document being edited (an unclosed
* string ends at the line end); null off a dependency name or version.
*/
export function npmDependencyAt(text: Text, offset: number): NpmDependency | null {
const source = text.sliceString(0, text.length);
const stack: Frame[] = [];
let pos = 0;
let i = 0;
// Only the manifest's own sections count: `overrides` or `scripts` objects with a
// `dependencies` key of their own are one level deeper and never match.
const inSection = () => stack.length === 2 && stack[1]!.object && SECTIONS.has(stack[1]!.owner ?? "");
while (i < source.length) {
const ch = source[i]!;
const here = pos;
const width = ch.codePointAt(0)! >= 0x10000 ? 2 : 1;
pos += width;
i += width;
if (ch === "{" || ch === "[") {
const parent = stack[stack.length - 1];
const owner = parent?.object && parent.expectingValue ? parent.pendingKey : null;
if (parent?.object && parent.expectingValue) {
parent.expectingValue = false;
parent.pendingKey = null;
}
stack.push({ object: ch === "{", pendingKey: null, expectingValue: false, owner });
} else if (ch === "}" || ch === "]") {
stack.pop();
} else if (ch === ":") {
const frame = stack[stack.length - 1];
if (frame?.object) frame.expectingValue = true;
} else if (ch === ",") {
const frame = stack[stack.length - 1];
if (frame?.object) {
frame.pendingKey = null;
frame.expectingValue = false;
}
} else if (ch === '"') {
const from = here + 1;
let content = "";
let to = from;
while (i < source.length) {
const next = source[i]!;
if (next === '"' || next === "\n" || next === "\r") break;
const w = next.codePointAt(0)! >= 0x10000 ? 2 : 1;
i += w;
pos += w;
if (next === "\\" && i < source.length) {
const escaped = source[i]!;
const w = escaped.codePointAt(0)! >= 0x10000 ? 2 : 1;
i += w;
pos += w;
content += escaped;
} else {
content += next;
}
to = pos;
}
if (source[i] === '"') {
i++;
pos++;
}
const frame = stack[stack.length - 1];
if (!frame?.object) continue;
if (frame.expectingValue) {
if (
inSection() &&
from <= offset &&
offset <= to &&
isPackageName(frame.pendingKey ?? "") &&
isVersionRange(content)
)
return { package: frame.pendingKey!, part: "version", from, to };
frame.expectingValue = false;
} else if (inSection() && from <= offset && offset <= to && isPackageName(content)) {
return { package: content, part: "name", from, to };
} else {
frame.pendingKey = content;
}
}
}
return null;
}
const dirname = (path: string): string => {
const slash = path.lastIndexOf("/");
return slash < 0 ? path : slash === 0 ? "/" : path.slice(0, slash);
};
/** null when the path does not exist (the probe rejects for directories' absence). */
const entryKind = (path: string): Promise<"file" | "dir" | "symlink" | null> =>
call(commands.fsEntryKind(path)).catch(() => null);
/**
* The reference at `offset` in a `package.json` manifest: the installed package the entry
* names — its own `package.json` for a name, its folder for a version — or a missing
* reference when it is not installed. Null outside a manifest, off a dependency entry, or
* without a desktop file system.
*/
export async function npmDependencyReference(text: Text, offset: number, path: string): Promise<Reference | null> {
if (!isTauri() || !MANIFEST.test(path)) return null;
const entry = npmDependencyAt(text, offset);
if (!entry) return null;
const { package: pkg, part, from, to } = entry;
for (let dir = dirname(path); ; dir = dirname(dir)) {
const installed = `${dir}/node_modules/${pkg}`;
// oxlint-disable-next-line no-await-in-loop -- each level is probed only when the level below has no package
if (await entryKind(installed)) {
// The name is the declaration: the package's own manifest opens. A version points
// at the entry as a whole: the package folder is revealed in the project view.
const manifest = `${installed}/package.json`;
return part === "name" &&
// oxlint-disable-next-line no-await-in-loop -- only reached once the package is found
(await entryKind(manifest)) === "file"
? { kind: "file", from, to, path: manifest }
: { kind: "folder", from, to, path: installed };
}
const parent = dirname(dir);
if (parent === dir) return { kind: "missing", from, to, value: pkg };
}
}