Files
RuneStone/tests/unit/workspace/noteIndex.spec.ts
T
Knotty Wyvern f32f60b540 Add a workspace session for marks, renames, the index, and events
Phase 4d. session.svelte.ts holds the workspace state of each window:
the marks, the note index, renames, and typed change events. It
replaces refreshToken.

- One rename path: session.rename serves the tree, the note title, the
  rename command, the link menu, plugins, and the template manager.
  Open documents, plugin views, the index, and the marks follow it.
  A title rename, the rename command, and a plugin rename now also
  move pins and bookmarks.
- marksStore.svelte.ts is the only writer of .runestone/marks.json.
  Changes run in order from the latest marks. A change from another
  window reloads the marks.
- The note index updates only the paths that change, does not rescan
  on window focus, reads in batches of 64, and keeps links, not text.
- Plugins also hear about .runestone/ changes from other windows.
- The outline uses the heading parser of heading links and Read, so
  lines in code blocks are no longer headings.
- New note is above New file in the tree menu (card a6032af5).
- New workspace/session smoke test and new unit tests for the index
  and the outline.

pnpm check, pnpm test (347 of 347), and the full smoke suite pass,
except workspace/manageTemplates, which failed one time under load and
passed on retry and 4 of 4 times alone.
2026-10-28 11:28:54 -07:00

210 lines
11 KiB
TypeScript

import test from "node:test";
import assert from "node:assert/strict";
import { WorkspaceNoteIndex, type NoteIndexIO } from "../../../src/lib/workspace/noteIndex.ts";
function workspace(files: Map<string, string>): NoteIndexIO {
return {
async list(folder) {
const prefix = folder ? `${folder}/` : "";
const entries = new Map<string, { rel_path: string; kind: "file" | "folder" }>();
for (const path of files.keys()) {
if (!path.startsWith(prefix)) continue;
const suffix = path.slice(prefix.length), separator = suffix.indexOf("/");
const rel_path = separator < 0 ? path : prefix + suffix.slice(0, separator);
entries.set(rel_path, { rel_path, kind: separator < 0 ? "file" : "folder" });
}
return [...entries.values()];
},
async read(path) {
if (!files.has(path)) throw new Error("File missing");
return files.get(path)!;
},
};
}
test("wiki names resolve anywhere and duplicate names require a path", async () => {
const index = new WorkspaceNoteIndex();
await index.rebuild(workspace(new Map([
["deep/source.md", "[[Elsewhere]]\n[[Root]]"], ["unrelated/nested/Elsewhere.md", ""], ["Root.md", ""],
])));
assert.deepEqual(index.resolve("deep/source.md", "Elsewhere", "wiki"), { status: "resolved", path: "unrelated/nested/Elsewhere.md" });
assert.deepEqual(index.resolve("deep/source.md", "Root#Heading", "wiki"), { status: "resolved", path: "Root.md" });
index.update("deep/Elsewhere.md", "");
assert.deepEqual(index.resolve("deep/source.md", "Elsewhere", "wiki"), { status: "ambiguous", candidates: ["deep/Elsewhere.md", "unrelated/nested/Elsewhere.md"] });
assert.equal(index.backlinks("deep/Elsewhere.md").length, 0);
assert.deepEqual(index.resolve("deep/source.md", "./Elsewhere", "wiki"), { status: "resolved", path: "deep/Elsewhere.md" });
index.update("documents/Other.mdown", "[[Root]]");
assert.deepEqual(index.resolve("deep/source.md", "Other", "wiki"), { status: "resolved", path: "documents/Other.mdown" });
assert.equal(index.backlinks("Root.md").length, 2);
index.update("documents/Version 1.2.md", "");
assert.deepEqual(index.resolve("deep/source.md", "Version 1.2", "wiki"), { status: "resolved", path: "documents/Version 1.2.md" });
});
test("explicit relative links do not fall back and cannot escape the workspace", () => {
const index = new WorkspaceNoteIndex();
for (const path of ["source.md", "deep/source.md", "Target.md", "deep/folder/Target.md", "folder/Target.md", "deep/Name with spaces.md"]) index.update(path, "");
assert.deepEqual(index.resolve("deep/source.md", "./Target", "wiki"), { status: "missing" });
assert.deepEqual(index.resolve("deep/source.md", "./Target.md", "md"), { status: "missing" });
assert.deepEqual(index.resolve("deep/source.md", "../Target", "wiki"), { status: "resolved", path: "Target.md" });
assert.deepEqual(index.resolve("deep/source.md", "/Target", "wiki"), { status: "resolved", path: "Target.md" });
assert.equal(index.resolve("deep/source.md", "folder/Target", "wiki").status, "ambiguous");
assert.deepEqual(index.resolve("deep/source.md", "Name%20with%20spaces.md#part", "md"), { status: "resolved", path: "deep/Name with spaces.md" });
assert.deepEqual(index.resolve("deep/source.md", "..\\Target.md", "md"), { status: "resolved", path: "Target.md" });
assert.equal(index.resolve("deep/source.md", "../../Target", "wiki").status, "missing");
assert.equal(index.resolve("source.md", "../Target", "wiki").status, "missing");
assert.equal(index.resolve("source.md", "https://example.test", "md").status, "external");
assert.equal(index.resolve("source.md", "//example.test/Target", "md").status, "external");
});
test("backlinks index wiki aliases, inline and reference Markdown links with source lines", () => {
const index = new WorkspaceNoteIndex();
index.update("Target.md", "");
index.update("source.md", [
"[[Target|Alias]]", "[Target](Target.md#Section)", "[Named][id]", "[id][]", "[id]", "", "[id]: Target.md", "",
"`[[Target]]`", "![picture](Target.md)", "![[Target]]", "\\[[Target]]", "<!-- [[Target]] -->", "```md", "[[Target]]", "```",
].join("\n"));
assert.deepEqual(index.backlinks("Target.md").map(link => [link.sourcePath, link.line, link.kind]), [
["source.md", 1, "wiki"], ["source.md", 2, "md"], ["source.md", 3, "md"], ["source.md", 4, "md"], ["source.md", 5, "md"],
]);
index.update("Target.md", "[Local section](#Heading)");
assert.equal(index.backlinks("Target.md").length, 5);
});
test("backlinks follow edits, create, file and folder moves, rename, and deletion", () => {
const index = new WorkspaceNoteIndex();
index.update("folder/source.md", "[[Target]]\n[Target](../Target.md)");
assert.deepEqual(index.backlinks("Target.md"), []);
index.update("Target.md", "");
assert.equal(index.backlinks("Target.md").length, 2);
index.update("folder/source.md", "[[Target]]");
assert.equal(index.backlinks("Target.md").length, 1);
index.rename("folder", "other/deep");
assert.equal(index.backlinks("Target.md")[0].sourcePath, "other/deep/source.md");
index.rename("Target.md", "notes/Target.md");
assert.equal(index.backlinks("notes/Target.md").length, 1);
index.rename("notes/Target.md", "notes/Renamed.md");
assert.equal(index.backlinks("notes/Renamed.md").length, 0);
index.update("other/deep/source.md", "[[Renamed]]");
assert.equal(index.backlinks("notes/Renamed.md").length, 1);
index.remove("other");
assert.equal(index.backlinks("notes/Renamed.md").length, 0);
index.remove("notes/Renamed.md");
assert.equal(index.resolve("", "Renamed", "wiki").status, "missing");
});
test("moving a relative-link source changes its target without rewriting Markdown", () => {
const index = new WorkspaceNoteIndex();
index.update("Target.md", "");
index.update("folder/Target.md", "");
index.update("source.md", "[Target](./Target.md)");
assert.equal(index.backlinks("Target.md").length, 1);
index.rename("source.md", "folder/source.md");
assert.equal(index.backlinks("Target.md").length, 0);
assert.equal(index.backlinks("folder/Target.md").length, 1);
});
test("rebuild replaces deleted paths and uses live drafts", async () => {
const files = new Map([["Target.md", ""], ["source.md", "[[Target]]"]]);
const index = new WorkspaceNoteIndex();
await index.rebuild(workspace(files));
assert.equal(index.backlinks("Target.md").length, 1);
files.delete("source.md");
files.set("elsewhere/source.md", "Old content");
const result = await index.rebuild(workspace(files), new Map([["elsewhere/source.md", "[[Target]]"]]));
assert.equal(result.committed, true);
assert.equal(result.indexed, 2);
assert.deepEqual(result.errors, []);
assert.deepEqual(index.backlinks("Target.md").map(link => link.sourcePath), ["elsewhere/source.md"]);
index.clear();
assert.equal(index.size, 0);
await index.rebuild(workspace(files));
assert.equal(index.size, 2);
});
test("updates during a rebuild survive its disk snapshot", async () => {
const files = new Map([["Target.md", ""], ["source.md", "[[Target]]"]]);
const io = workspace(files);
let release!: () => void;
const barrier = new Promise<void>(resolve => release = resolve);
const index = new WorkspaceNoteIndex();
const rebuild = index.rebuild({ ...io, read: async path => { await barrier; return io.read(path); } });
await Promise.resolve();
index.update("source.md", "No link");
index.update("new.md", "[[Target]]");
index.rename("new.md", "moved.md");
release();
await rebuild;
assert.deepEqual(index.backlinks("Target.md").map(link => link.sourcePath), ["moved.md"]);
});
test("workspace clear and a newer rebuild reject stale async results", async () => {
let release!: () => void;
const barrier = new Promise<void>(resolve => release = resolve);
const index = new WorkspaceNoteIndex();
const slow = index.rebuild({ list: async () => { await barrier; return [{ rel_path: "old.md", kind: "file" }]; }, read: async () => "" });
index.clear();
await index.rebuild(workspace(new Map([["new.md", ""]])));
release();
assert.equal((await slow).committed, false);
assert.equal(index.resolve("", "old", "wiki").status, "missing");
assert.deepEqual(index.resolve("", "new", "wiki"), { status: "resolved", path: "new.md" });
});
test("read and list failures report incomplete coverage and remain rebuildable", async () => {
const index = new WorkspaceNoteIndex();
const io = workspace(new Map([["Target.md", ""], ["source.md", "[[Target]]"], ["blocked/note.md", ""]]));
const result = await index.rebuild({
list: async folder => { if (folder === "blocked") throw new Error("Folder unavailable"); return io.list(folder); },
read: async path => { if (path === "source.md") throw new Error("File unavailable"); return io.read(path); },
});
assert.deepEqual(result.errors.map(error => [error.path, error.operation]), [["blocked", "list"], ["source.md", "read"]]);
assert.equal(index.backlinks("Target.md").length, 0);
await index.rebuild(io);
assert.equal(index.backlinks("Target.md").length, 1);
});
test("watcher paths update, add, and remove notes without a full rebuild", async () => {
const files = new Map([["Target.md", ""], ["source.md", "[[Target]]"], ["old/note.md", "[[Target]]"]]);
const index = new WorkspaceNoteIndex();
await index.rebuild(workspace(files));
assert.equal(index.backlinks("Target.md").length, 2);
let lists = 0;
const io = workspace(files), counted: NoteIndexIO = { ...io, list: folder => { lists++; return io.list(folder); } };
files.set("source.md", "No link now");
files.delete("old/note.md");
files.set("new/deeper/linker.md", "[[Target]]");
await index.refresh(counted, ["source.md", "old/note.md", "old", "new"]);
assert.deepEqual(index.backlinks("Target.md").map(link => link.sourcePath), ["new/deeper/linker.md"]);
assert.equal(lists, 4, "The root, the deleted folder, the new folder, and its subfolder");
});
test("refresh keeps the unsaved links of an open draft", async () => {
const files = new Map([["Target.md", ""], ["draft.md", ""]]);
const index = new WorkspaceNoteIndex();
await index.rebuild(workspace(files));
index.update("draft.md", "[[Target]]");
await index.refresh(workspace(files), ["draft.md"], new Map([["draft.md", "[[Target]]"]]));
assert.equal(index.backlinks("Target.md").length, 1);
});
test("a rename keeps the links of the moved note", async () => {
const index = new WorkspaceNoteIndex();
await index.rebuild(workspace(new Map([["Target.md", ""], ["notes/source.md", "[Up](../Target.md)"]])));
index.rename("notes", "archive");
assert.deepEqual(index.backlinks("Target.md").map(link => link.sourcePath), ["archive/source.md"]);
});
test("bulk reads use batches of 64 and read a file that is too large for a batch alone", async () => {
const files = new Map([["Target.md", ""], ...Array.from({ length: 70 }, (_, i) => [`n${i}.md`, "[[Target]]"] as [string, string])]);
const io = workspace(files), batches: number[] = [], singles: string[] = [];
const index = new WorkspaceNoteIndex();
await index.rebuild({
...io,
read: async path => { singles.push(path); return io.read(path); },
readMany: async paths => { batches.push(paths.length); return paths.map(path => path === "n5.md" ? { path, error: "The batch exceeds the 16 MiB limit." } : { path, source: files.get(path)! }); },
});
assert.deepEqual(batches, [64, 7]);
assert.deepEqual(singles, ["n5.md"]);
assert.equal(index.backlinks("Target.md").length, 70);
});