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
+35
View File
@@ -0,0 +1,35 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { CompletionHub, eligible } from '../../../src/lib/completion/hub.ts';
import type { CompletionSnapshot } from '../../../src/lib/completion/contracts.ts';
const snapshot = (): CompletionSnapshot => ({ documentId: 'doc', revision: 1, text: 'The ', caret: 4, selectionEnd: 4, focused: true, kind: 'prose' });
const tick = () => new Promise(resolve => setTimeout(resolve, 0));
test('sensitive fields, composition, selections, code blocks and link targets are excluded', () => {
assert(eligible(snapshot()));
for (const change of [{ sensitive: true }, { composing: true }, { readOnly: true }, { selectionEnd: 0 }, { focused: false }]) assert(!eligible({ ...snapshot(), ...change }));
for (const text of ['```js\nlet ', '[name](http', '| cell ', '`source', '---\nname: ']) assert(!eligible({ ...snapshot(), text, caret: text.length, selectionEnd: text.length }));
assert(eligible({ ...snapshot(), kind: 'code', text: 'let ', caret: 4 }));
});
test('a new revision blocks stale insertion even when the provider ignores cancellation', async () => {
const hub = new CompletionHub(); let state = snapshot(), emit!: (text: string) => void, finish!: (text: string) => void, visible = '', edits = 0;
hub.registerProvider({ id: 'model', complete: (_request, publish) => { emit = publish; return new Promise(resolve => finish = resolve); } });
const field = hub.registerSurface({ id: 'field', snapshot: () => state, preview: text => visible = text || '', insert: () => { edits++; return true; } });
field.request(); emit('harbor'); assert.equal(visible, 'harbor');
state = { ...state, revision: 2, text: 'The old ', caret: 8, selectionEnd: 8 };
assert.equal(field.accept(), false); finish('late'); await tick(); assert.equal(visible, ''); assert.equal(edits, 0); field.dispose();
});
test('acceptance is explicit and provider removal clears all surfaces', async () => {
const hub = new CompletionHub(); let visible = '', inserted = '';
const remove = hub.registerProvider({ id: 'model', complete: async () => 'quiet harbor' });
const field = hub.registerSurface({ id: 'field', snapshot, preview: text => visible = text || '', insert: text => { inserted = text; return true; } });
field.request(); await tick(); assert.equal(inserted, ''); assert.equal(visible, 'quiet harbor');
assert(field.accept(true)); assert.equal(inserted, 'quiet '); assert.equal(visible, '');
field.request(); await tick(); remove(); assert.equal(visible, ''); assert.equal(field.accept(), false); field.dispose();
});
test('moving between fields cancels the previous request', async () => {
const hub = new CompletionHub(); const signals: AbortSignal[] = [];
hub.registerProvider({ id: 'model', complete: request => { signals.push(request.signal); return new Promise(() => {}); } });
const a = hub.registerSurface({ id: 'a', snapshot, preview() {}, insert: () => true });
const b = hub.registerSurface({ id: 'b', snapshot, preview() {}, insert: () => true });
a.request(); b.request(); assert(signals[0].aborted); assert(!signals[1].aborted); a.dispose(); b.dispose();
});
+138
View File
@@ -0,0 +1,138 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
import type { PluginApi } from "../../../src/lib/plugins/sdk.ts";
function fixture() {
let writes = 0;
const session = new ExternalSession("org.test.demo", {
workspace: { list: async () => [], read: async () => "original", write: async () => { writes++; } },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
}, () => {}, () => {});
return { session, writes: () => writes };
}
test("native Markdown discovery remains optional and is revoked on disable", async () => {
let api!: PluginApi;
let scans = 0;
const session = new ExternalSession("org.test.scan", {
workspace: { list: async () => [], listMarkdown: async () => { scans++; return ["Notes/task.md"]; }, read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
}, () => {}, () => {});
await session.start({ activate(value) { api = value; } });
assert.deepEqual(await api.workspace.listMarkdown!(), ["Notes/task.md"]);
await session.stop();
assert.throws(() => api.workspace.listMarkdown!(), /disabled/);
assert.equal(scans, 1);
const old = fixture().session;
await old.start({ activate(value) { assert.equal(value.workspace.listMarkdown, undefined); } });
await old.stop();
});
test("external commands run and all host access stops before cleanup", async () => {
const { session, writes } = fixture(); let api!: PluginApi; let ran = 0;
await session.start({ activate(value) {
api = value;
api.registerCommand({ id: "run", title: "Run", run: () => { ran++; } });
api.registerView({ id: "view", title: "View", mount: () => {} });
api.onDispose(() => { assert(api.signal.aborted); assert.throws(() => api.workspace.read("x"), /disabled/); });
} });
await session.run("run"); assert.equal(ran, 1);
assert.throws(() => api.workspace.write("x", "new", undefined!), /original/);
await api.workspace.write("x", "new", "original"); assert.equal(writes(), 1);
await session.stop(); assert.equal(session.commands.size, 0); assert.equal(session.views.size, 0);
await assert.rejects(session.run("run"), /disabled/);
assert.throws(() => api.settings.read(), /disabled/);
});
test("async activation cleanup runs once even when disabled before activation finishes", async () => {
const { session } = fixture(); let resolve!: () => void; let cleaned = 0;
const gate = new Promise<void>(done => resolve = done);
const start = session.start({ async activate() { await gate; return () => { cleaned++; }; } });
await Promise.resolve();
const stopped = session.stop(); resolve();
await Promise.all([start, stopped]); await session.stop(); assert.equal(cleaned, 1);
});
test("failed cleanup does not skip other callbacks and blocks successful shutdown", async () => {
const { session } = fixture(); const calls: number[] = [];
await session.start({ activate(api) {
api.onDispose(() => { calls.push(1); });
api.onDispose(() => { calls.push(2); throw new Error("Cleanup failed"); });
api.onDispose(() => { calls.push(3); });
} });
await assert.rejects(session.stop(), /Cleanup failed/); assert.deepEqual(calls, [3, 2, 1]);
});
test("duplicate contribution IDs fail and partial activation can be cleaned", async () => {
const { session } = fixture(); let cleaned = false;
await assert.rejects(session.start({ activate(api) {
api.onDispose(() => { cleaned = true; });
api.registerCommand({ id: "run", title: "Run", run() {} });
api.registerCommand({ id: "run", title: "Again", run() {} });
} }), /duplicate/);
await session.stop(); assert(cleaned); assert.equal(session.commands.size, 0);
});
test("view disposal is idempotent and participates in plugin shutdown", async () => {
const { session } = fixture(); let cleaned = 0; let cleared = 0;
await session.start({ activate(api) { api.registerView({ id: "view", title: "View", mount: () => () => { cleaned++; } }); } });
const cleanup = await session.mount("view", { replaceChildren() { cleared++; } } as unknown as HTMLElement);
await session.stop(); await cleanup(); assert.equal(cleaned, 1); assert.equal(cleared, 1);
});
test("shutdown waits for view cleanup that already started when the view closed", async () => {
const { session } = fixture(); let done!: () => void; let cleaned = false;
const gate = new Promise<void>(resolve => done = resolve);
await session.start({ activate(api) { api.registerView({ id: "view", title: "View", mount: () => async () => { await gate; cleaned = true; } }); } });
const cleanup = await session.mount("view", { replaceChildren() {} } as unknown as HTMLElement);
const closing = cleanup(); await Promise.resolve();
let stopped = false; const stopping = session.stop().then(() => { stopped = true; });
await Promise.resolve(); await Promise.resolve(); assert.equal(stopped, false);
done(); await Promise.all([closing, stopping]); assert(cleaned);
});
test("cleanup returned by late activation still blocks shutdown when it fails", async () => {
const { session } = fixture(); let done!: () => void;
const gate = new Promise<void>(resolve => done = resolve);
const starting = session.start({ async activate() { await gate; return () => { throw new Error("Late cleanup failed"); }; } });
await Promise.resolve(); const stopping = session.stop(); done();
await assert.rejects(starting, /Late cleanup failed/); await assert.rejects(stopping, /Late cleanup failed/);
});
test("batch workspace reads remain optional and stop when the plugin is disabled", async () => {
let api!: PluginApi;
let calls = 0;
const rows = [{ path: "Card.md", source: "Card source" }, { path: "Missing.md", error: "File not found" }];
const session = new ExternalSession("org.test.batch", {
workspace: { list: async () => [], read: async () => "", write: async () => {},
readMany: async paths => { calls++; assert.deepEqual(paths, ["Card.md", "Missing.md"]); return rows; } },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
}, () => {}, () => {});
await session.start({ activate(value) { api = value; } });
assert.deepEqual(await api.workspace.readMany!(["Card.md", "Missing.md"]), rows);
await session.stop();
assert.throws(() => api.workspace.readMany!(["Card.md"]), /disabled/);
assert.equal(calls, 1);
const old = fixture().session;
await old.start({ activate(value) { assert.equal(value.workspace.readMany, undefined); } });
await old.stop();
});
test("view launch selects a default while explicit opens preserve their target", async () => {
const opened: string[] = [];
let api!: PluginApi;
const session = new ExternalSession("org.test.launch", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
}, () => {}, id => { opened.push(id); });
await session.start({ activate(value) {
api = value;
api.registerView({ id: "all", title: "All", launch: async () => { api.openView("board"); }, mount() {} });
api.registerView({ id: "board", title: "Board", mount() {} });
assert.throws(() => api.registerView({ id: "invalid", title: "Invalid", launch: true as never, mount() {} }), /launch handler/);
} });
await session.launch("all");
api.openView("all");
await session.launch("board");
assert.deepEqual(opened, ["board", "all", "board"]);
await assert.rejects(session.launch("missing"), /Unknown plugin view/);
await session.stop();
await assert.rejects(session.launch("all"), /disabled/);
});
+85
View File
@@ -0,0 +1,85 @@
import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { pluginAccess } from "../../../src/lib/plugins/access.ts";
import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
import type { PluginApi, PluginCommand, PluginView } from "../../../src/lib/plugins/sdk.ts";
const view = (id: string, extra: Partial<PluginView> = {}): PluginView => ({ id, title: id, mount() {}, ...extra });
const command = (id: string, extra: Partial<PluginCommand> = {}): PluginCommand => ({ id, title: id, run() {}, ...extra });
test("plugin access separates settings, launchers, and commands without reading titles", () => {
const tools = pluginAccess("org.example.test", [command("open", { category: "open" }), command("configure")], [view("preferences", { settings: true }), view("tasks"), view("instance", { launcher: false })]);
assert.deepEqual(tools.map(({ id, surface }) => [id, surface]), [["open", "open"], ["configure", "commands"], ["preferences", "settings"], ["tasks", "open"]]);
});
test("installed RuneStone packages retain access before their next package update", () => {
assert.equal(pluginAccess("runestone.local-autocomplete", [], [view("settings")])[0].surface, "settings");
assert.equal(pluginAccess("org.example.test", [], [view("settings")])[0].surface, "open");
assert.equal(pluginAccess("runestone.local-autocomplete", [], [view("settings", { settings: false })])[0].surface, "open");
});
test("the browser ID gets the same access rules as any other owner", () => {
// The built-in browser sets `category` and `launcher` itself. The old Browser package had no special rules left.
assert.deepEqual(pluginAccess("runestone.browser", [command("new-tab")], [view("tab-123")]).map(({ id, surface }) => [id, surface]), [["new-tab", "commands"], ["tab-123", "open"]]);
assert.deepEqual(pluginAccess("runestone.browser", [command("new-tab", { category: "open", icon: "globe" })], [view("tab-123", { launcher: false })]).map(({ id, surface, icon }) => [id, surface, icon]), [["new-tab", "open", "globe"]]);
});
test("command launchers retain the plugin action icon", () => {
const tools = pluginAccess("runestone.git", [command("graph", { category: "open", icon: "git" })], []);
assert.equal(tools[0].icon, "git");
assert.equal(tools[0].surface, "open");
});
test("settings listeners are removable and revoked before plugin cleanup", async () => {
let api!: PluginApi, notify!: () => void;
let received = 0, disposed = 0;
const session = new ExternalSession("org.example.settings", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
assets: { read: async () => new Uint8Array() },
settings: { read: async () => null, write: async () => {}, subscribe(listener) { notify = listener; return () => { disposed++; }; } },
}, () => {}, () => {});
await session.start({ activate(value) { api = value; } });
const off = api.settings.subscribe!(() => { received++; });
notify(); assert.equal(received, 1);
await off(); await off(); assert.equal(disposed, 1);
api.settings.subscribe!(() => { received++; });
await session.stop(); notify();
assert.equal(received, 1); assert.equal(disposed, 2);
assert.throws(() => api.settings.subscribe!(() => {}), /disabled/);
});
test("invalid access metadata fails registration", async () => {
for (const activate of [
(api: PluginApi) => api.registerCommand(command("invalid", { category: "unknown" as "open" })),
(api: PluginApi) => api.registerView(view("invalid", { settings: "yes" as unknown as boolean })),
(api: PluginApi) => api.registerView(view("invalid", { launcher: "yes" as unknown as boolean })),
]) {
const session = new ExternalSession("org.example.invalid", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
assets: { read: async () => new Uint8Array() }, settings: { read: async () => null, write: async () => {} },
}, () => {}, () => {});
await assert.rejects(session.start({ activate }), /category|boolean/);
await session.stop();
}
});
test("settings windows permit model checks and cancellation", () => {
const capability = JSON.parse(readFileSync(new URL("../../../src-tauri/capabilities/settings.json", import.meta.url), "utf8"));
for (const permission of ["allow-completion-request", "allow-completion-cancel", "allow-plugins-data"]) assert(capability.permissions.includes(permission));
});
test("view mount context distinguishes Settings from editor and dialog views", async () => {
const surfaces: string[] = [];
const session = new ExternalSession("org.example.context", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
assets: { read: async () => new Uint8Array() }, settings: { read: async () => null, write: async () => {} },
}, () => {}, () => {});
await session.start({ activate(api) { api.registerView(view("settings", { mount(_element, context) { surfaces.push(context!.surface); } })); } });
const target = { replaceChildren() {} } as unknown as HTMLElement;
const disposeView = await session.mount("settings", target);
await disposeView();
const disposeSettings = await session.mount("settings", target, undefined, "settings");
await disposeSettings(); await session.stop();
assert.deepEqual(surfaces, ["view", "settings"]);
});
@@ -0,0 +1,96 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
import type { PluginApi, PluginDocumentType } from "../../../src/lib/plugins/sdk.ts";
const services = {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
};
const type: PluginDocumentType = {
id: "board", title: "Board", icon: "kanban", extensions: ["md"],
identify: (_path, source) => source === "board" ? { id: "stable" } : null,
create: { label: "New board", defaultName: "Untitled board", extension: "md", contents: () => "board" },
mount: () => {},
};
test("document renames pass the stable identity and stop after shutdown", async () => {
let api!: PluginApi;
const calls: unknown[] = [];
const session = new ExternalSession("fixture", services, () => {}, () => {}, undefined, undefined,
async (document, name) => { calls.push({ document, name }); return "Renamed.md"; });
await session.start({ activate(value) { api = value; } });
assert.equal(await api.renameDocument!({ id: "stable", path: "Board.md" }, "Renamed"), "Renamed.md");
assert.deepEqual(calls, [{ document: { id: "stable", path: "Board.md" }, name: "Renamed" }]);
await session.stop();
assert.throws(() => api.renameDocument!({ id: "stable", path: "Board.md" }, "Other"), /disabled/);
assert.equal(calls.length, 1);
});
test("binary document registration preserves bytes and revokes reads on shutdown", async () => {
let api!: PluginApi;
const bytes = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0xff, 0x00]);
const paths: string[] = [];
const session = new ExternalSession("fixture", {
...services, workspace: { ...services.workspace, readBytes: async path => { paths.push(path); return bytes; } },
}, () => {}, () => {});
await session.start({ activate(value) {
api = value;
api.registerDocumentType({ ...type, id: "pdf", extensions: ["pdf"], content: "binary", create: undefined });
} });
assert.equal(session.documentTypes.get("pdf")?.content, "binary");
assert.deepEqual(await api.workspace.readBytes!("report.pdf"), bytes);
assert.deepEqual(paths, ["report.pdf"]);
assert.throws(() => api.registerDocumentType({ ...type, content: "invalid" as "binary" }), /content type/);
await session.stop();
assert.throws(() => api.workspace.readBytes!("report.pdf"), /disabled/);
});
test("document types have independent registrations and reject invalid creation actions", async () => {
let api!: PluginApi;
const session = new ExternalSession("fixture", services, () => {}, () => {});
await session.start({ activate(value) { api = value; api.registerDocumentType(type); } });
assert.equal(session.documentTypes.get("board")?.identify("Board.md", "board")?.id, "stable");
assert.equal(session.documentTypes.get("board")?.identify("Note.md", "plain"), null);
assert.throws(() => api.registerDocumentType(type), /duplicate/);
assert.throws(() => api.registerDocumentType({ ...type, id: "other", create: { ...type.create!, extension: "exe" } }), /Invalid document creation/);
await session.stop();
assert.equal(session.documentTypes.size, 0);
assert.throws(() => api.registerDocumentType(type), /disabled/);
});
test("two document mounts retain independent context and clean up once", async () => {
const mounted: string[] = [], cleaned: string[] = [];
const session = new ExternalSession("fixture", services, () => {}, () => {});
await session.start({ activate(api) {
api.registerDocumentType({ ...type, mount(_node, context) { mounted.push(context.path); return () => { cleaned.push(context.id); }; } });
} });
const element = () => ({ replaceChildren() {} }) as unknown as HTMLElement;
const first = await session.mount("board", element(), { id: "first", path: "One.md" });
await session.mount("board", element(), { id: "second", path: "Two.md" });
assert.deepEqual(mounted, ["One.md", "Two.md"]);
await first(); await first();
assert.deepEqual(cleaned, ["first"]);
await session.stop();
assert.deepEqual(cleaned, ["first", "second"]);
});
test("document opening and workspace subscriptions stop with their plugin", async () => {
let api!: PluginApi;
let listener: (() => void) | undefined;
let notifications = 0, removed = 0;
const opened: string[] = [];
const session = new ExternalSession("fixture", {
...services,
workspace: { ...services.workspace, subscribe(callback) { listener = callback; return () => { removed++; }; } },
}, () => {}, () => {}, undefined, async path => { opened.push(path); });
await session.start({ activate(value) { api = value; api.workspace.subscribe!(() => { notifications++; }); } });
await api.openDocument("Board.md"); listener!();
assert.deepEqual(opened, ["Board.md"]);
assert.equal(notifications, 1);
await session.stop(); listener!();
assert.equal(notifications, 1);
assert.equal(removed, 1);
assert.throws(() => api.openDocument("Board.md"), /disabled/);
});
@@ -0,0 +1,44 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
import { ContributionRegistry } from "../../../src/lib/plugins/registry.ts";
import type { PluginApi } from "../../../src/lib/plugins/sdk.ts";
test("file access stops before plugin cleanup, and plugins get no Git API", async () => {
const calls: unknown[] = [];
let api!: PluginApi;
const session = new ExternalSession("test.files", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
openFile: async path => { calls.push(path); },
}, () => {}, () => {}, new ContributionRegistry());
await session.start({ activate(value) { api = value; } });
// Git is a native feature of RuneStone. The plugin API has no Git member.
assert.equal("git" in api, false);
await api.openFile!("notes.md");
assert.deepEqual(calls, ["notes.md"]);
await session.stop();
assert.throws(() => api.openFile!("notes.md"), /disabled/);
});
test("view replacement rejects unknown destinations and stops after disposal", async () => {
let api!: PluginApi;
const calls: unknown[] = [];
const session = new ExternalSession("test.boards", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
}, () => {}, () => {}, new ContributionRegistry(), undefined, undefined, undefined,
(current, next) => calls.push([current, next]), (document, next) => calls.push([document, next]));
await session.start({ activate(value) {
api = value;
for (const id of ["a", "b"]) api.registerView({ id, title: id, placement: "editor", mount() {} });
api.registerView({ id: "sidebar", title: "Sidebar", placement: "sidebar", navigation: true, icon: "git", mount() {} });
} });
api.replaceView!("a", "b");
api.replaceDocumentWithView!({ id: "legacy", path: "Board.md" }, "b");
assert.deepEqual(calls, [["a", "b"], [{ id: "legacy", path: "Board.md" }, "b"]]);
assert.throws(() => api.replaceView!("missing", "b"), /Unknown/);
assert.throws(() => api.replaceDocumentWithView!({ id: "legacy", path: "Board.md" }, "missing"), /Unknown/);
await session.stop();
assert.throws(() => api.replaceView!("a", "b"), /disabled/);
});
@@ -0,0 +1,80 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ExternalSession, type SessionServices } from "../../../src/lib/plugins/externalSession.ts";
import { ContributionRegistry } from "../../../src/lib/plugins/registry.ts";
import { ServiceHub } from "../../../src/lib/plugins/services.ts";
import type { FilesTransport, PluginApi } from "../../../src/lib/plugins/sdk.ts";
const base: SessionServices = {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
};
async function start(id: string, services: Partial<SessionServices>) {
let api!: PluginApi;
const session = new ExternalSession(id, { ...base, ...services }, () => {}, () => {}, new ContributionRegistry());
await session.start({ activate(value) { api = value; } });
return { api, session };
}
test("folder grant calls check shutdown before and after the native request", async () => {
const calls: unknown[][] = [];
let finish: ((value: unknown) => void) | undefined;
const grant = { id: "7f1b6f6e-3c39-4b55-9f3e-4a3a6d1d7c11", path: "C:/Pictures/RuneStone Backgrounds", name: "RuneStone Backgrounds" };
const files: FilesTransport = {
chooseFolder: async options => { calls.push(["choose", options]); return grant; },
pictureFolder: async name => { calls.push(["picture", name]); return grant; },
grants: async () => [grant],
revoke: async id => { calls.push(["revoke", id]); return true; },
list: () => new Promise(resolve => { finish = resolve as (value: unknown) => void; }),
readBytes: async (id, name) => { calls.push(["read", id, name]); return new Uint8Array([1, 2]); },
readSidecar: async () => null,
writeSidecar: async (id, name, contents, expected) => { calls.push(["write", id, name, contents, expected]); },
};
const { api, session } = await start("org.test.slides", { files });
assert.deepEqual(await api.files!.chooseFolder({ title: "Images" }), grant);
assert.deepEqual(await api.files!.pictureFolder("Backgrounds"), grant);
assert.deepEqual(await api.files!.readBytes(grant.id, "a.png"), new Uint8Array([1, 2]));
await api.files!.writeSidecar(grant.id, ".runestone-backgrounds.json", "{}", null);
assert.equal(await api.files!.revoke(grant.id), true);
assert.deepEqual(calls, [["choose", { title: "Images" }], ["picture", "Backgrounds"], ["read", grant.id, "a.png"], ["write", grant.id, ".runestone-backgrounds.json", "{}", null], ["revoke", grant.id]]);
assert.throws(() => api.files!.readBytes("", "a.png"), /grant ID/);
assert.throws(() => api.files!.writeSidecar(grant.id, ".runestone-a.json", "{}", undefined as never), /expected/);
const pending = api.files!.list(grant.id);
await session.stop();
finish!([{ name: "a.png", size: 2 }]);
await assert.rejects(pending, /disabled/);
assert.throws(() => api.files!.grants(), /disabled/);
});
test("plugin services copy data, stop with their provider, and stop for a stopped consumer", async () => {
const serviceHub = new ServiceHub();
const boards = [{ id: "b1", name: "Roadmap" }];
const provider = await start("org.test.boards", { serviceHub });
const consumer = await start("org.test.slides", { serviceHub });
const changes: string[] = [];
consumer.api.services!.subscribe((plugin, name) => changes.push(`${plugin}/${name}`));
assert.equal(consumer.api.services!.get("org.test.boards", "boards"), null);
const handle = provider.api.services!.provide("boards", { list: () => boards });
assert.throws(() => provider.api.services!.provide("boards", { list: () => boards }), /already/);
assert.throws(() => provider.api.services!.provide("Bad Name", { list: () => boards }), /service name/);
const service = consumer.api.services!.get("org.test.boards", "boards")!;
const result = await service.list() as typeof boards;
assert.deepEqual(result, boards);
result[0].name = "Changed";
assert.equal(boards[0].name, "Roadmap", "the consumer receives a copy");
handle.notify();
assert.deepEqual(changes, ["org.test.boards/boards", "org.test.boards/boards"]);
await provider.session.stop();
assert.deepEqual(changes.at(-1), "org.test.boards/boards");
await assert.rejects(service.list(), /no longer available/);
assert.equal(consumer.api.services!.get("org.test.boards", "boards"), null);
const again = await start("org.test.boards", { serviceHub });
again.api.services!.provide("boards", { list: () => boards });
const fresh = consumer.api.services!.get("org.test.boards", "boards")!;
await consumer.session.stop();
await assert.rejects(fresh.list(), /disabled/);
const count = changes.length;
await again.session.stop();
assert.equal(changes.length, count, "a stopped consumer receives no notifications");
});
@@ -0,0 +1,64 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, mkdir, readFile, writeFile, rm, realpath } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
// @ts-ignore The build tool is a JavaScript module.
import { packagePlugin } from "../../../scripts/packagePlugin.mjs";
test("plugin packaging rejects invalid release inputs before writing an archive", async () => {
const root = await mkdtemp(join(tmpdir(), "runestone-packaging-"));
const source = join(root, "plugin"), output = join(root, "releases");
await mkdir(source);
const manifest = {
schemaVersion: 1, apiVersion: 1, id: "org.test.demo", name: "Demo", author: "Test",
description: "Test plugin", version: "1.0.0", entry: "main.js", access: "full-app",
};
const save = async (changes = {}) => writeFile(join(source, "plugin.json"), JSON.stringify({ ...manifest, ...changes }));
try {
await assert.rejects(packagePlugin(source, output), /plugin.json at its root/);
await save();
await assert.rejects(packagePlugin(source, output), /entry module is missing/);
await writeFile(join(source, "main.js"), "export function activate() {}");
for (const [changes, message] of [
[{ id: "../escape" }, /ID is invalid/],
[{ version: "1.0" }, /version such as/],
[{ version: "1.0.0A" }, /version such as/],
[{ version: "1.0.0a1" }, /version such as/],
[{ version: "1.0.0-beta" }, /version such as/],
[{ version: "1.0.0+build" }, /version such as/],
[{ entry: "../main.js" }, /compiled JavaScript/],
[{ apiVersion: 99 }, /Unsupported/],
[{ author: "" }, /valid author/],
] as const) {
await save(changes);
await assert.rejects(packagePlugin(source, output), message);
}
await save();
await assert.rejects(packagePlugin(source, source), /outside the plugin folder/);
await writeFile(join(source, "invalid file.txt"), "test");
await assert.rejects(packagePlugin(source, output), /Invalid package path/);
await rm(join(source, "invalid file.txt"));
await writeFile(join(root, "package.json"), JSON.stringify({ name: "test-plugin" }));
const path = await packagePlugin(source);
assert.equal(path, join(await realpath(output), "org.test.demo-1.0.0.zip"));
const first = await readFile(path);
await packagePlugin(source, output);
assert.deepEqual(await readFile(path), first);
await writeFile(join(source, "main.js"), "export function activate() { return 1; }");
await assert.rejects(packagePlugin(source), /different contents/);
assert.deepEqual(await readFile(path), first);
await writeFile(join(source, "main.js"), "export function activate() {}");
for (const version of ["0.2.28a", "0.2.28b", "0.2.28aa"]) {
await save({ version });
const hotfix = await packagePlugin(source, output);
assert.equal(hotfix, join(await realpath(output), `org.test.demo-${version}.zip`));
assert.ok((await readFile(hotfix)).length > 0);
assert.deepEqual(await readFile(path), first);
}
} finally {
// mkdtemp returns this test's unique directory under the operating system temp folder.
assert.equal(root.startsWith(join(tmpdir(), "runestone-packaging-")), true);
await rm(root, { recursive: true, force: true });
}
});
+87
View File
@@ -0,0 +1,87 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ContributionRegistry, pluginHost } from "../../../src/lib/plugins/registry.ts";
import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
import type { PluginApi } from "../../../src/lib/plugins/sdk.ts";
import type { Contributions } from "../../../src/lib/plugins/contracts.ts";
// A small test-only package. It contributes the browser, as the built-in browser module does.
const browser: Contributions["browser"] = { mountSettings: () => () => {}, mountBookmarks: () => () => {}, open: async () => false };
const activate = (api: PluginApi) => { api.contribute("browser", browser); };
const services = {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
};
test("optional workspace creation and reads stop when the plugin is disabled", async () => {
const files = new Map<string, string>();
let api!: PluginApi;
const session = new ExternalSession("workspace-test", {
...services,
workspace: {
...services.workspace,
readOptional: async path => files.get(path) ?? null,
create: async (path, contents) => { if (files.has(path)) throw new Error("exists"); files.set(path, contents); },
},
}, () => {}, () => {});
await session.start({ activate(value) { api = value; } });
assert.equal(await api.workspace.readOptional!("board.json"), null);
await api.workspace.create!("board.json", "{}");
assert.equal(await api.workspace.readOptional!("board.json"), "{}");
await assert.rejects(api.workspace.create!("board.json", "replacement"), /exists/);
await session.stop();
assert.throws(() => api.workspace.create!("other.json", "{}"), /disabled/);
assert.throws(() => api.workspace.readOptional!("board.json"), /disabled/);
assert.equal(files.size, 1);
});
test("core starts without optional features and package contributions end with their session", async () => {
assert.equal(pluginHost.get("browser"), undefined);
const registry = new ContributionRegistry();
const session = new ExternalSession("org.test.feature", services, () => {}, () => {}, registry);
await session.start({ activate });
assert.equal(registry.get("browser"), browser);
await session.stop();
assert.equal(registry.get("browser"), undefined);
const next = new ExternalSession("org.test.feature", services, () => {}, () => {}, registry);
await next.start({ activate });
assert.equal(registry.get("browser"), browser);
await next.stop();
assert.equal(registry.get("browser"), undefined);
});
test("unknown contribution keys are rejected", () => {
const registry = new ContributionRegistry();
// `terminal` was a contribution until the Terminal feature became native.
for (const key of ["tableFormulas", "git", "terminal"]) assert.throws(() => registry.register("old", key as keyof Contributions, browser as never), /Unknown plugin contribution/);
});
test("package contribution conflicts preserve the first owner and revoke access before cleanup", async () => {
const registry = new ContributionRegistry();
const first = new ExternalSession("first", services, () => {}, () => {}, registry);
const second = new ExternalSession("second", services, () => {}, () => {}, registry);
let api!: PluginApi;
await first.start({ activate(value) { api = value; activate(api); } });
const contribution = registry.get("browser");
await assert.rejects(second.start({ activate }), /already registered/);
await second.stop();
assert.equal(registry.get("browser"), contribution);
api.onDispose(() => {
assert.equal(registry.get("browser"), undefined);
assert.throws(() => api.contribute("browser", contribution!), /disabled/);
});
await first.stop();
});
test("partial activation and failed cleanup cannot retain feature contributions", async () => {
const registry = new ContributionRegistry();
const session = new ExternalSession("failed", services, () => {}, () => {}, registry);
await assert.rejects(session.start({ activate(api) {
activate(api);
api.onDispose(() => { throw new Error("Cleanup failed"); });
throw new Error("Activation failed");
} }), /Activation failed/);
await assert.rejects(session.stop(), /Cleanup failed/);
assert.equal(registry.get("browser"), undefined);
});
@@ -0,0 +1,26 @@
import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
type Capability = { windows: string[]; permissions: string[] };
const read = (file: string): string => readFileSync(new URL(`../../../${file}`, import.meta.url), "utf8");
const capability = (name: string): Capability => JSON.parse(read(`src-tauri/capabilities/${name}.json`));
test("browser windows have their own capability, a subset of the main window commands", () => {
const browser = capability("browser"), main = capability("default"), settings = capability("settings");
assert.deepEqual(browser.windows, ["browser-*"]);
for (const other of [main, settings]) assert(!other.windows.some(pattern => pattern.startsWith("browser")), "Only browser.json matches browser windows.");
const extra = browser.permissions.filter(permission => !main.permissions.includes(permission));
assert.deepEqual(extra, [], "browser.json grants only permissions that default.json also grants.");
// Browser windows run no installed plugin, so they need no workspace, file, plugin package, terminal, or Git access.
const denied = browser.permissions.filter(permission => /^allow-(workspace|git|pty|backgrounds|tab-transfer|completion|theme|settings-open)-|^allow-plugins-(?!snapshot$)|^(opener|dialog):/.test(permission));
assert.deepEqual(denied, []);
});
test("browser windows start only the built-in browser", () => {
// The capability split depends on this: a browser window never loads an installed plugin.
assert.match(read("src/routes/+page.svelte"), /startExternalPlugins\(\{ browserWindow \}\)/);
assert.match(read("src/lib/plugins/external.ts"), /if \(builtInPackages\.includes\(id\) \|\| browserWindow\) continue;/);
assert.match(read("src/lib/plugins/external.ts"), /if \(browserWindow && !builtIn\.browserWindow\) continue;/);
assert.match(read("src-tauri/src/browser.rs"), /let label = format!\("browser-\{\}", uuid::Uuid::new_v4\(\)\);/);
});