RuneStone 1.0.0

This commit is contained in:
Knotty Wyvern
2026-11-16 04:21:21 -07:00
commit b52eeb14a1
827 changed files with 241421 additions and 0 deletions
+36
View File
@@ -0,0 +1,36 @@
import assert from "node:assert/strict";
import test from "node:test";
import { chromeLayout, detectChrome, extensionOf, treeFileParts } from "../../../src/lib/workspace/chrome.ts";
test("markdown files open in writing chrome", () => {
assert.equal(detectChrome("notes/inbox.md"), "Writing");
assert.equal(detectChrome("README.markdown"), "Writing");
});
test("scripts open in ide chrome", () => {
assert.equal(detectChrome("src/hello.py"), "Source");
assert.equal(detectChrome("tools/setup.sh"), "Source");
assert.equal(detectChrome("Makefile"), "Source");
});
test("writing chrome wraps and hides the code gutters", () => {
assert.deepEqual(chromeLayout("Writing"), { wrap: true, gutters: false, activeLine: false });
});
test("ide chrome shows the code gutters and does not wrap", () => {
assert.deepEqual(chromeLayout("Source"), { wrap: false, gutters: true, activeLine: true });
});
test("extensionOf reads the last suffix", () => {
assert.equal(extensionOf("a/b.c.py"), "py");
assert.equal(extensionOf(".gitignore"), "");
});
test("treeFileParts splits a display name from its extension", () => {
assert.deepEqual(treeFileParts("inbox.md"), { label: "inbox", ext: "md" });
assert.deepEqual(treeFileParts("chrome_extensions.json"), {
label: "chrome_extensions",
ext: "json",
});
assert.deepEqual(treeFileParts(".gitignore"), { label: ".gitignore", ext: "" });
});
@@ -0,0 +1,29 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { documentSessionKey, parseDocumentSession, restoreDocumentSession } from "../../../src/lib/workspace/documentSession.ts";
test("document sessions isolate workspaces and discard unsafe or duplicate paths", () => {
assert.notEqual(documentSessionKey("C:\\one"), documentSessionKey("C:\\two"));
assert.equal(parseDocumentSession("invalid"), null);
assert.equal(parseDocumentSession('{"version":2,"documents":[]}'), null);
assert.deepEqual(parseDocumentSession(JSON.stringify({ version: 1, activePath: "b.md", documents: [
{ path: "b.md", pinned: true, contents: "unsaved" }, { path: "a.md" }, { path: "b.md" },
{ path: "../outside.md" }, { path: "C:\\outside.md" }, { path: "empty:test" }, null,
] })), { version: 1, activePath: "b.md", documents: [{ path: "b.md", pinned: true }, { path: "a.md", pinned: false }] });
});
test("restoration keeps order and active tab when a missing file fails", async () => {
const opened: string[] = [];
const session = parseDocumentSession(JSON.stringify({ version: 1, activePath: "c.md",
documents: ["b.md", "missing.md", "c.md", "a.md"].map(path => ({ path })) }))!;
const active = await restoreDocumentSession(session, async item => {
if (item.path === "missing.md") throw new Error("Not found");
opened.push(item.path);
});
assert.deepEqual(opened, ["b.md", "c.md", "a.md"]);
assert.equal(active, "c.md");
assert.equal(await restoreDocumentSession({ ...session, activePath: "missing.md" }, async item => {
if (item.path === "missing.md") throw new Error("Not found");
}), "b.md");
assert.equal(await restoreDocumentSession(session, async () => { throw new Error("Unavailable"); }), null);
});
+429
View File
@@ -0,0 +1,429 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { Documents } from "../../../src/lib/workspace/documents.svelte.ts";
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>(done => resolve = done);
return { promise, resolve };
}
const entry = (path: string) => ({ rel_path: path, name: path, kind: "file" as const });
function setup() {
const disk = new Map([["note.md", "original"], ["script.py", "print('hello')"]]);
const io = {
read: async (path: string) => { if (!disk.has(path)) throw new Error("missing"); return disk.get(path)!; },
write: async (path: string, contents: string, expected: string) => {
if (disk.get(path) !== expected) throw new Error("conflict");
disk.set(path, contents);
},
image: async () => "data:image/png;base64,",
kind: () => "text" as const,
chrome: () => "Writing" as const,
};
const docs = new Documents(io, () => {});
return { docs, disk, io };
}
test("imported tabs retain unsaved text and preserve pinned empty tabs", async () => {
const { docs } = setup();
docs.newTab();
const empty = docs.active!;
docs.togglePin(empty.relPath);
const source = setup().docs;
await source.open(entry("note.md"));
source.edit(source.active!.id, "unsaved source text");
source.togglePin("note.md");
assert.equal(docs.importTab(source.active!), true);
assert.equal(docs.active!.contents, "unsaved source text");
assert.equal(docs.active!.saved, "original");
assert.equal(docs.active!.pinned, true);
assert.notEqual(docs.active!.id, source.active!.id);
assert.ok(docs.buffers.some(tab => tab.id === empty.id));
assert.equal(docs.importTab({ ...source.active!, contents: "different" }), false);
assert.equal(docs.active!.contents, "unsaved source text");
});
test("background loading for a split preserves the selected document and its unsaved edits", async () => {
const { docs } = setup();
await docs.open(entry("note.md"));
const first = docs.active!;
docs.edit(first.id, "unsaved text");
await docs.open(entry("script.py"), "background");
assert.equal(docs.active, first);
assert.equal(first.contents, "unsaved text");
assert.equal(docs.buffers.length, 2);
await assert.rejects(docs.open(entry("missing.md"), "background"));
assert.equal(docs.active, first);
docs.select("script.py");
assert.equal(docs.active?.relPath, "script.py");
});
test("tab moves preserve selection, dirty buffers, and in-flight saves", async () => {
const { docs, io, disk } = setup();
await docs.open(entry("note.md"));
const note = docs.active!;
docs.edit(note.id, "my edits");
docs.setChrome("Source");
await docs.open(entry("script.py"));
docs.newTab();
const blank = docs.active!;
const gate = deferred<void>();
const write = io.write;
io.write = async (...args) => { await gate.promise; await write(...args); };
const pending = docs.save(note.id);
await Promise.resolve();
docs.move(note.relPath, 2);
assert.deepEqual(docs.buffers.map(b => b.relPath), ["script.py", blank.relPath, "note.md"]);
assert.equal(docs.active, blank);
assert.equal(docs.buffers[2], note);
assert.equal(note.contents, "my edits");
assert.equal(note.saved, "original");
assert.equal(note.chromeOverride, "Source");
docs.move(blank.relPath, 0);
assert.equal(docs.active, blank);
gate.resolve();
await pending;
assert.equal(disk.get("note.md"), "my edits");
docs.close(blank.relPath);
assert.equal(docs.activePath, "script.py");
});
test("tab moves ignore stale paths and invalid indices and clamp to the tab strip", async () => {
const { docs } = setup();
await docs.open(entry("note.md"));
await docs.open(entry("script.py"));
docs.move("missing.md", 0);
docs.move("script.py", NaN);
docs.move("script.py", 0.5);
assert.deepEqual(docs.buffers.map(b => b.relPath), ["note.md", "script.py"]);
docs.move("script.py", -1);
assert.deepEqual(docs.buffers.map(b => b.relPath), ["script.py", "note.md"]);
docs.move("script.py", 99);
assert.deepEqual(docs.buffers.map(b => b.relPath), ["note.md", "script.py"]);
docs.dispose();
docs.move("script.py", 0);
assert.deepEqual(docs.buffers.map(b => b.relPath), ["note.md", "script.py"]);
});
test("empty tabs are independent, preserve dirty documents, and never access disk", async () => {
const { docs, io } = setup();
await docs.open(entry("note.md"));
const note = docs.active!;
docs.edit(note.id, "keep my edits");
docs.newTab();
const first = docs.active!;
docs.newTab();
const second = docs.active!;
assert.equal(first.kind, "empty");
assert.equal(second.kind, "empty");
assert.notEqual(first.relPath, second.relPath);
assert.equal(note.contents, "keep my edits");
docs.select(first.relPath);
docs.close(first.relPath);
assert.equal(docs.active, second);
docs.close(note.relPath);
io.read = io.image = async () => { assert.fail("empty tabs must not read disk"); };
io.write = async () => { assert.fail("empty tabs must not write disk"); };
docs.edit(second.id, "ignored");
await docs.refresh();
await docs.save(second.id);
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
assert.equal(docs.dirty, false);
assert.equal(second.diskError, undefined);
docs.close(second.relPath);
assert.equal(docs.activePath, null);
});
test("opening a file fills the active empty tab in place and failed reads preserve it", async () => {
const { docs } = setup();
docs.newTab();
const first = docs.active!;
docs.newTab();
const second = docs.active!;
docs.select(first.relPath);
await assert.rejects(docs.open(entry("missing.md")), /missing/);
assert.equal(docs.active, first);
await docs.open(entry("note.md"));
assert.deepEqual(docs.buffers.map(b => b.relPath), ["note.md", second.relPath]);
docs.select(second.relPath);
await docs.open(entry("note.md"));
assert.equal(docs.buffers.length, 2);
assert.equal(docs.activePath, "note.md");
});
test("a new empty tab stays selected when an earlier file read finishes", async () => {
const { docs, io } = setup();
const gate = deferred<string>();
io.read = () => gate.promise;
const pending = docs.open(entry("note.md"));
docs.newTab();
const blank = docs.active!;
gate.resolve("note");
await pending;
assert.equal(docs.active, blank);
assert.equal(docs.buffers.length, 2);
});
test("clean buffers follow agent edits; dirty buffers retain both versions", async () => {
const { docs, disk } = setup();
await docs.open(entry("note.md"));
disk.set("note.md", "agent version");
await docs.refresh();
assert.equal(docs.active?.contents, "agent version");
docs.edit(docs.active!.id, "my version");
disk.set("note.md", "agent version 2");
await docs.refresh();
assert.equal(docs.active?.contents, "my version");
assert.equal(docs.active?.diskContents, "agent version 2");
await assert.rejects(docs.save(docs.active!.id), /Resolve/);
docs.resolve(docs.active!.id, false);
await docs.save(docs.active!.id);
assert.equal(disk.get("note.md"), "my version");
});
test("typing during a save remains unsaved", async () => {
const { docs, io, disk } = setup();
await docs.open(entry("note.md"));
const gate = deferred<void>();
const write = io.write;
io.write = async (...args) => { await gate.promise; return write(...args); };
docs.edit(docs.active!.id, "first edit");
const pending = docs.save(docs.active!.id);
await Promise.resolve();
docs.edit(docs.active!.id, "second edit");
gate.resolve();
await pending;
assert.equal(disk.get("note.md"), "first edit");
assert.equal(docs.active!.saved, "first edit");
assert.equal(docs.active!.contents, "second edit");
assert.equal(docs.dirty, true);
});
test("concurrent saves serialize and finish at the latest edit", async () => {
const { docs, io, disk } = setup();
await docs.open(entry("note.md"));
const gate = deferred<void>();
const write = io.write;
io.write = async (...args) => { await gate.promise; return write(...args); };
docs.edit(docs.active!.id, "first");
const first = docs.save(docs.active!.id);
await Promise.resolve();
docs.edit(docs.active!.id, "latest");
const second = docs.save(docs.active!.id);
const third = docs.save(docs.active!.id);
gate.resolve();
await Promise.all([first, second, third]);
assert.equal(disk.get("note.md"), "latest");
assert.equal(docs.dirty, false);
});
test("latest navigation wins even when earlier reads finish later", async () => {
const { docs, io } = setup();
const gate = deferred<string>();
const read = io.read;
io.read = path => path === "note.md" ? gate.promise : read(path);
const first = docs.open(entry("note.md"));
await docs.open(entry("script.py"));
gate.resolve("note");
await first;
assert.equal(docs.activePath, "script.py");
});
test("duplicate opens share one document and do not lose edits", async () => {
const { docs } = setup();
await Promise.all([docs.open(entry("note.md")), docs.open(entry("note.md"))]);
assert.equal(docs.buffers.length, 1);
docs.edit(docs.active!.id, "unsaved");
await docs.open(entry("script.py"));
await docs.open(entry("note.md"));
assert.equal(docs.active!.contents, "unsaved");
});
test("current-tab navigation replaces the selected tab in place; new-tab navigation keeps it", async () => {
const { docs, disk } = setup();
disk.set("third.md", "third");
await docs.open(entry("note.md"));
await docs.open(entry("script.py"), "new");
docs.select("note.md");
await docs.open(entry("third.md"), "current");
assert.deepEqual(docs.buffers.map(b => b.relPath), ["third.md", "script.py"]);
assert.equal(docs.activePath, "third.md");
await docs.open(entry("script.py"), "current");
assert.deepEqual(docs.buffers.map(b => b.relPath), ["third.md", "script.py"]);
assert.equal(docs.activePath, "script.py");
});
test("current-tab navigation preserves edits made while the next file is loading", async () => {
const { docs, io } = setup();
await docs.open(entry("note.md"));
const note = docs.active!;
const gate = deferred<string>();
io.read = () => gate.promise;
const pending = docs.open(entry("script.py"), "current");
docs.edit(note.id, "keep these edits");
gate.resolve("script");
await pending;
assert.equal(docs.buffers.length, 2);
assert.equal(note.contents, "keep these edits");
assert.equal(docs.activePath, "script.py");
});
test("failed current-tab navigation keeps the active document", async () => {
const { docs } = setup();
await docs.open(entry("note.md"), "current");
await assert.rejects(docs.open(entry("missing.md"), "current"), /missing/);
assert.equal(docs.buffers.length, 1);
assert.equal(docs.activePath, "note.md");
});
test("a late current-tab read cannot replace a more recently selected tab", async () => {
const { docs, io } = setup();
await docs.open(entry("note.md"));
const gate = deferred<string>();
io.read = () => gate.promise;
const pending = docs.open(entry("script.py"), "current");
docs.select("note.md");
gate.resolve("script");
await pending;
assert.equal(docs.activePath, "note.md");
assert.equal(docs.buffers[0].relPath, "note.md");
});
test("removed files retain text and block accidental recreation", async () => {
const { docs, disk } = setup();
await docs.open(entry("note.md"));
docs.edit(docs.active!.id, "precious text");
disk.delete("note.md");
await docs.refresh();
assert.equal(docs.active!.contents, "precious text");
assert.match(docs.active!.diskError!, /unavailable/);
await assert.rejects(docs.save(docs.active!.id));
});
test("disposing a workspace ignores late open results", async () => {
const { docs, io } = setup();
const gate = deferred<string>();
io.read = () => gate.promise;
const pending = docs.open(entry("note.md"));
docs.dispose(); gate.resolve("late");
await pending;
assert.equal(docs.buffers.length, 0);
});
test("renaming a folder preserves document identity and dirty state", async () => {
const { docs } = setup();
await docs.open(entry("note.md"));
const id = docs.active!.id;
docs.edit(id, "edits"); docs.rename("note.md", "notes/moved.md");
assert.equal(docs.activePath, "notes/moved.md");
assert.equal(docs.active!.id, id);
assert.equal(docs.dirty, true);
});
test("autosave writes changed background tabs once and skips clean or reverted text", async () => {
const { docs, io, disk } = setup();
const writes: string[] = [];
const write = io.write;
io.write = async (...args) => { writes.push(args[0]); await write(...args); };
await docs.open(entry("note.md"));
const note = docs.active!;
docs.edit(note.id, "background edit");
await docs.open(entry("script.py"));
docs.edit(docs.active!.id, "temporary edit");
docs.edit(docs.active!.id, docs.active!.saved);
assert.deepEqual(await docs.autosave(), { saved: ["note.md"], failed: [] });
assert.equal(disk.get("note.md"), "background edit");
await docs.autosave();
await docs.save(note.id);
assert.deepEqual(writes, ["note.md"]);
});
test("autosave skips in-flight saves and preserves edits for the next pass", async () => {
const { docs, io, disk } = setup();
await docs.open(entry("note.md"));
const gate = deferred<void>();
const write = io.write;
let writes = 0;
io.write = async (...args) => { writes++; await gate.promise; await write(...args); };
docs.edit(docs.active!.id, "first");
const pending = docs.autosave();
await Promise.resolve();
docs.edit(docs.active!.id, "still typing");
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
gate.resolve();
await pending;
assert.equal(writes, 1);
assert.equal(disk.get("note.md"), "first");
assert.equal(docs.dirty, true);
await docs.autosave();
assert.equal(writes, 2);
assert.equal(disk.get("note.md"), "still typing");
});
test("autosave skips known conflicts and unavailable files", async () => {
const { docs, io, disk } = setup();
await docs.open(entry("note.md"));
const note = docs.active!;
docs.edit(note.id, "my note");
await docs.open(entry("script.py"));
docs.edit(docs.active!.id, "my script");
disk.set("note.md", "external edit");
disk.delete("script.py");
await docs.refresh();
io.write = async () => { assert.fail("blocked files must not be written"); };
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
assert.equal(note.contents, "my note");
assert.equal(note.diskContents, "external edit");
assert.equal(docs.active!.contents, "my script");
assert.equal(docs.dirty, true);
});
test("an autosave failure preserves edits, saves other files, and can be retried", async () => {
const { docs, io, disk } = setup();
await docs.open(entry("note.md"));
const note = docs.active!;
docs.edit(note.id, "my note");
await docs.open(entry("script.py"));
docs.edit(docs.active!.id, "my script");
const write = io.write;
io.write = async (...args) => {
if (args[0] === "note.md") throw new Error("disk full");
await write(...args);
};
const result = await docs.autosave();
assert.deepEqual(result.saved, ["script.py"]);
assert.equal(result.failed[0].path, "note.md");
assert.match(String(result.failed[0].error), /disk full/);
assert.equal(note.saved, "original");
assert.equal(note.contents, "my note");
assert.equal(disk.get("script.py"), "my script");
io.write = write;
await docs.autosave();
assert.equal(disk.get("note.md"), "my note");
assert.equal(docs.dirty, false);
});
test("autosave cannot overwrite an external edit even before the watcher refreshes", async () => {
const { docs, disk } = setup();
await docs.open(entry("note.md"));
docs.edit(docs.active!.id, "my note");
disk.set("note.md", "external edit");
const result = await docs.autosave();
assert.equal(result.failed.length, 1);
assert.equal(disk.get("note.md"), "external edit");
assert.equal(docs.active!.contents, "my note");
assert.equal(docs.dirty, true);
});
test("closed documents and disposed workspaces are not autosaved", async () => {
const { docs, io } = setup();
await docs.open(entry("note.md"));
docs.edit(docs.active!.id, "discarded");
docs.close("note.md");
io.write = async () => { assert.fail("discarded edits must not be written"); };
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
await docs.open(entry("script.py"));
docs.edit(docs.active!.id, "disposed");
docs.dispose();
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
});
+209
View File
@@ -0,0 +1,209 @@
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);
});
+12
View File
@@ -0,0 +1,12 @@
import assert from "node:assert/strict";
import test from "node:test";
import { buildOutline } from "../../../src/lib/workspace/outline.ts";
test("the Markdown outline skips code blocks and properties and shows rendered text", () => {
const source = "---\ntitle: Note\n---\n# **Bold** title\n\n```sh\n# not a heading\n```\n\nSetext\n------\n";
assert.deepEqual(buildOutline("note.md", source), [{ level: 1, text: "Bold title", line: 4 }, { level: 2, text: "Setext", line: 10 }]);
});
test("code files list their definitions", () => {
assert.deepEqual(buildOutline("tool.py", "import os\ndef run():\n pass\n"), [{ level: 1, text: "run", line: 2 }]);
});
+76
View File
@@ -0,0 +1,76 @@
import assert from "node:assert/strict";
import test from "node:test";
import { planRename, planTitleRename, planMarkdownTitleRename, planDocumentTitleRename } from "../../../src/lib/workspace/renamePath.ts";
test("rename in a folder keeps the parent", () => {
assert.deepEqual(planRename("notes/a.md", "b.md"), {
action: "rename",
to: "notes/b.md",
});
});
test("same name is a no-op", () => {
assert.deepEqual(planRename("notes/a.md", "a.md"), { action: "noop" });
});
test("path separators are rejected", () => {
assert.deepEqual(planRename("notes/a.md", "foo/bar"), {
action: "error",
message: "Name cannot contain a path separator",
});
assert.deepEqual(planRename("notes/a.md", "foo\\bar"), {
action: "error",
message: "Name cannot contain a path separator",
});
});
test("empty name is rejected", () => {
assert.deepEqual(planRename("notes/a.md", " "), {
action: "error",
message: "Name is empty",
});
});
test("root file rename stays at the root", () => {
assert.deepEqual(planRename("inbox.md", "todo.md"), {
action: "rename",
to: "todo.md",
});
});
test("title rename keeps the existing extension", () => {
assert.deepEqual(planTitleRename("notes/inbox.md", "hello"), {
action: "rename",
to: "notes/hello.md",
});
assert.deepEqual(planTitleRename("notes/inbox.md", "inbox"), { action: "noop" });
});
test("title rename keeps a typed extension", () => {
assert.deepEqual(planTitleRename("notes/inbox.md", "hello.txt"), {
action: "rename",
to: "notes/hello.txt",
});
});
test("writing titles preserve Markdown extensions and allow dots in names", () => {
assert.deepEqual(planMarkdownTitleRename("notes/inbox.md", "Release 1.2"), { action: "rename", to: "notes/Release 1.2.md" });
assert.deepEqual(planMarkdownTitleRename("notes/inbox.MD", " Renamed.md "), { action: "rename", to: "notes/Renamed.MD" });
assert.deepEqual(planMarkdownTitleRename("inbox.markdown", "Renamed"), { action: "rename", to: "Renamed.markdown" });
assert.deepEqual(planMarkdownTitleRename("inbox.mdown", "Renamed"), { action: "rename", to: "Renamed.mdown" });
assert.deepEqual(planMarkdownTitleRename("notes/inbox.md", "inbox"), { action: "noop" });
assert.deepEqual(planMarkdownTitleRename("notes/inbox.md.md", "inbox.md"), { action: "noop" });
for (const name of ["", " ", ".md", "../escape", "folder/note", "folder\\note"]) {
assert.equal(planMarkdownTitleRename("notes/inbox.md", name).action, "error", name);
}
});
test("document names retain their format and cannot hide or move the file", () => {
assert.deepEqual(planDocumentTitleRename("Projects/Board.md", "Renamed"), { action: "rename", to: "Projects/Renamed.md" });
assert.deepEqual(planDocumentTitleRename("Projects/Board.md", "Release 1.2"), { action: "rename", to: "Projects/Release 1.2.md" });
assert.deepEqual(planDocumentTitleRename("Projects/Board.MD", "Renamed.md"), { action: "rename", to: "Projects/Renamed.MD" });
assert.deepEqual(planDocumentTitleRename("Report.pdf", "Next.pdf"), { action: "rename", to: "Next.pdf" });
assert.deepEqual(planDocumentTitleRename("Board.md", "Board"), { action: "noop" });
for (const name of ["", " ", ".md", ".hidden", "../escape", "folder/name", "folder\\name", "a:b", "a?b"])
assert.equal(planDocumentTitleRename("Board.md", name).action, "error", name);
});
+26
View File
@@ -0,0 +1,26 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { TAB_TRANSFER_ID, parseTabTransfer } from '../../../src/lib/workspace/tabTransfer.ts';
const buffer = { id: 'one', relPath: 'a.md', name: 'a.md', kind: 'text', contents: 'Unsaved', saved: 'Saved' };
test('A buffer transfer needs a path, its text, and its saved text', () => {
assert.deepEqual(parseTabTransfer(JSON.stringify({ buffer, reading: true })), { buffer, reading: true });
assert.equal(parseTabTransfer(JSON.stringify({ buffer })).reading, false);
for (const field of ['relPath', 'contents', 'saved'] as const) {
assert.throws(() => parseTabTransfer(JSON.stringify({ buffer: { ...buffer, [field]: 1 } })), /Invalid tab transfer/);
}
});
test('A plugin transfer needs a state object, and other payloads are invalid', () => {
const plugin = { owner: 'test.plugin', id: 'board' };
assert.deepEqual(parseTabTransfer(JSON.stringify({ plugin, reading: false })), { plugin, reading: false });
for (const payload of ['{', 'null', '[]', '{}', '{"plugin":"text"}', '{"buffer":null}']) {
assert.throws(() => parseTabTransfer(payload), /Invalid tab transfer/, payload);
}
});
test('Transfer IDs are UUIDs', () => {
assert.ok(TAB_TRANSFER_ID.test(crypto.randomUUID()));
for (const id of ['', '../x', 'runestone.tab-transfer.1']) assert.ok(!TAB_TRANSFER_ID.test(id), id);
});