Plugin runtime cost: - Remove the timed plugin scan. Windows scan at start, on focus, on Refresh, and on plugins-changed. - Keep one package check for each plugin folder. Read and hash the files again only when the entry names, sizes, or modification times change. Enable and load always read all files. An asset read checks the SHA-256 hash of its file. - A changed package still stops and needs a new enable decision. Add tests for the cache, for changes that keep the metadata, and for the enable decision. - Replace the 50 ms wait loops of update and removal with a condition variable. The limit stays at 10 seconds. Command names, arguments, and results do not change. Content security policy: - Set app.security.csp in tauri.conf.json. Keep Tauri from adding nonces to style-src. - Add CSP mode to the smoke tests (pnpm smoke --csp). The dev server sends the same policy with each HTML page, and the harness fails a test on a policy violation. - Decode data URLs without fetch in the background frame test. Capabilities: - Give browser windows their own capability. They load no installed plugin. Add a unit test and a browser window smoke test for the command set. Document the scans, the hash cache, the policy, and the window capabilities.
313 lines
16 KiB
JavaScript
313 lines
16 KiB
JavaScript
// Shared setup for the browser smoke tests: Playwright, the Tauri IPC mock, and output folders.
|
|
// Run a test with `pnpm smoke <name>`, or run its file with Node while `pnpm dev` serves the app.
|
|
import { createRequire } from "node:module";
|
|
import { mkdir } from "node:fs/promises";
|
|
import { fileURLToPath } from "node:url";
|
|
import path from "node:path";
|
|
|
|
export const repoRoot = fileURLToPath(new URL("../../../", import.meta.url));
|
|
export const smokeUrl = process.env.SMOKE_URL || "http://127.0.0.1:1420";
|
|
|
|
/** The path of a sibling plugin checkout, for example pluginRepo("RuneStone_Git"). */
|
|
export function pluginRepo(folder) {
|
|
return path.resolve(process.env.RUNESTONE_PLUGIN_REPOS || path.join(repoRoot, ".."), folder);
|
|
}
|
|
|
|
/** Playwright, from PLAYWRIGHT_MODULE or the project dependency. */
|
|
export function playwright() {
|
|
return createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || "playwright");
|
|
}
|
|
|
|
/** True in CSP mode (`pnpm smoke --csp`). The dev server then sends the app's content security policy. */
|
|
export const cspMode = process.env.RUNESTONE_CSP === "1";
|
|
/** The content security policy violations of all pages in CSP mode. `runSmoke` fails when this list is not empty. */
|
|
export const cspViolations = [];
|
|
const CSP_PREFIX = "[csp-violation] ";
|
|
// This function runs in each page and frame. Violations inside workers do not reach it.
|
|
function reportCspViolations(prefix) {
|
|
addEventListener("securitypolicyviolation", event => {
|
|
console.error(prefix + JSON.stringify({ directive: event.effectiveDirective, blocked: event.blockedURI, source: event.sourceFile, line: event.lineNumber, sample: event.sample, page: location.href }));
|
|
}, true);
|
|
}
|
|
/** Record the violations of a browser context or a page. */
|
|
async function watchCsp(target) {
|
|
await target.addInitScript(reportCspViolations, CSP_PREFIX);
|
|
target.on("console", message => {
|
|
if (message.text().startsWith(CSP_PREFIX)) cspViolations.push(message.text().slice(CSP_PREFIX.length));
|
|
});
|
|
}
|
|
|
|
/** Start headless Chromium. CHROME_PATH selects an installed browser. In CSP mode, each new context and page records violations. */
|
|
export async function launchBrowser(options = {}) {
|
|
const executablePath = process.env.CHROME_PATH;
|
|
const browser = await playwright().chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}), ...options });
|
|
if (cspMode) {
|
|
const { newContext, newPage } = { newContext: browser.newContext.bind(browser), newPage: browser.newPage.bind(browser) };
|
|
browser.newContext = async (...args) => { const context = await newContext(...args); await watchCsp(context); return context; };
|
|
browser.newPage = async (...args) => { const page = await newPage(...args); await watchCsp(page); return page; };
|
|
}
|
|
return browser;
|
|
}
|
|
|
|
/**
|
|
* Open a page that collects uncaught page errors in `page.errors`, and console errors and warnings in `page.console`.
|
|
* `target` is a browser or a browser context. A context page keeps the context viewport unless `viewport` is given.
|
|
*/
|
|
export async function openPage(target, { viewport, timeout = 10000, ...options } = {}) {
|
|
const isContext = typeof target.browser === "function";
|
|
const page = isContext ? await target.newPage() : await target.newPage({ viewport: viewport ?? { width: 1440, height: 1000 }, ...options });
|
|
if (isContext && viewport) await page.setViewportSize(viewport);
|
|
page.setDefaultTimeout(timeout);
|
|
page.errors = [];
|
|
page.console = [];
|
|
page.on("pageerror", error => page.errors.push(error.message));
|
|
page.on("console", message => {
|
|
if (["error", "warning"].includes(message.type())) page.console.push(`${message.type()}: ${message.text()}`);
|
|
});
|
|
return page;
|
|
}
|
|
|
|
/** Create and return output/smoke/<name>/ for screenshots and reports. */
|
|
export async function outputDir(name) {
|
|
const dir = path.join(repoRoot, "output", "smoke", name);
|
|
await mkdir(dir, { recursive: true });
|
|
return dir;
|
|
}
|
|
|
|
/** Wait two animation frames, so layout and Svelte updates settle. */
|
|
export function settle(page) {
|
|
return page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
|
}
|
|
|
|
/**
|
|
* Mock the Tauri IPC layer before the app loads. The mock handles the event plugin.
|
|
*
|
|
* `commands(test)` runs in the page and returns a map from command name to handler `(args, test) => result`.
|
|
* It cannot use variables from the test file. Pass data through `state`, which must be JSON.
|
|
* `test` is also `window.__TEST__`: `{ state, calls, emit(event, payload), label, workspace(options), settings(section), writeSettings(section, value) }`.
|
|
* A command without a handler throws "Unhandled IPC", or returns null when `strict` is false.
|
|
*
|
|
* Default handlers serve the settings file (`settings_*`) and tab transfers (`tab_transfer_*`). `commands` can replace them.
|
|
* All pages of one browser context share their state: the settings file and the offers are in localStorage under
|
|
* test keys, and a BroadcastChannel sends `settings-changed` to every page and `tab-transfer-accepted` to the source page.
|
|
* Without a settings file, the app migrates the old localStorage keys, so a test can seed preferences there before the first load.
|
|
* `test.settings(section)` reads a section of the file. `test.writeSettings(section, value)` acts as a write from another window.
|
|
*/
|
|
export function mockTauri(target, { label = "main", state = {}, commands, strict = true } = {}) {
|
|
const options = JSON.stringify({ label, state, strict });
|
|
return target.addInitScript(`(${installMock})(${options}, ${commands ? commands.toString() : "undefined"});`);
|
|
}
|
|
|
|
// This function runs in the page. Keep it self-contained.
|
|
function installMock(options, commands) {
|
|
let sequence = 0;
|
|
const callbacks = new Map();
|
|
const listeners = new Map();
|
|
const emit = (event, payload) => {
|
|
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
|
};
|
|
|
|
// An in-memory workspace: `files` maps workspace paths to text. Folders come from the paths and `folders`.
|
|
// Create, rename, and delete emit "workspace-event". Writes emit it only when `writeEvents` is true.
|
|
const workspace = ({ root = "C:\\workspace", name = root.split(/[\\/]/).pop(), files = {}, folders = [], watchMode = "native", recent = [], writeEvents = false } = {}) => {
|
|
const store = files instanceof Map ? files : new Map(Object.entries(files));
|
|
const dirs = new Set(folders);
|
|
const parentOf = rel => rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : "";
|
|
const allFolders = () => {
|
|
const result = new Set(dirs);
|
|
for (const rel of store.keys()) for (let dir = parentOf(rel); dir; dir = parentOf(dir)) result.add(dir);
|
|
return result;
|
|
};
|
|
const changed = (kind, paths) => emit("workspace-event", { root, kind, paths });
|
|
const handlers = {
|
|
workspace_last_path: () => root,
|
|
workspace_recent: () => recent,
|
|
workspace_open: () => ({ root, name, watch_mode: watchMode }),
|
|
workspace_list: ({ rel = "" }) => {
|
|
const children = [];
|
|
for (const dir of allFolders()) if (parentOf(dir) === rel) children.push({ name: dir.split("/").pop(), rel_path: dir, kind: "folder" });
|
|
for (const file of store.keys()) if (parentOf(file) === rel) children.push({ name: file.split("/").pop(), rel_path: file, kind: "file" });
|
|
return children;
|
|
},
|
|
workspace_list_markdown: () => [...store.keys()].filter(rel => /\.md$/i.test(rel)).sort(),
|
|
workspace_read: ({ rel }) => {
|
|
if (!store.has(rel)) throw new Error(`Missing file: ${rel}`);
|
|
return store.get(rel);
|
|
},
|
|
workspace_read_many: ({ paths }) => paths.map(rel => store.has(rel) ? { path: rel, source: store.get(rel) } : { path: rel, error: "Missing file" }),
|
|
workspace_write: ({ rel, contents }) => {
|
|
store.set(rel, contents);
|
|
if (writeEvents) changed("modify", [rel]);
|
|
return null;
|
|
},
|
|
workspace_create: ({ rel, kind }) => {
|
|
if (store.has(rel) || allFolders().has(rel)) throw new Error("Destination exists");
|
|
if (kind === "folder") dirs.add(rel); else store.set(rel, "");
|
|
changed("create", [rel]);
|
|
return null;
|
|
},
|
|
workspace_rename: ({ from, to }) => {
|
|
if (store.has(to) || allFolders().has(to)) throw new Error("Destination exists");
|
|
for (const [rel, text] of [...store]) {
|
|
if (rel === from || rel.startsWith(from + "/")) { store.delete(rel); store.set(to + rel.slice(from.length), text); }
|
|
}
|
|
for (const dir of [...dirs]) if (dir === from || dir.startsWith(from + "/")) { dirs.delete(dir); dirs.add(to + dir.slice(from.length)); }
|
|
changed("rename", [from, to]);
|
|
return null;
|
|
},
|
|
workspace_delete: ({ rel }) => {
|
|
for (const key of [...store.keys()]) if (key === rel || key.startsWith(rel + "/")) store.delete(key);
|
|
for (const dir of [...dirs]) if (dir === rel || dir.startsWith(rel + "/")) dirs.delete(dir);
|
|
changed("remove", [rel]);
|
|
return null;
|
|
},
|
|
workspace_search: ({ query }) => {
|
|
const hits = [];
|
|
for (const [rel, text] of store) text.split("\n").forEach((line, index) => {
|
|
if (query && line.toLowerCase().includes(query.toLowerCase())) hits.push({ rel_path: rel, line: index + 1, text: line });
|
|
});
|
|
return hits;
|
|
},
|
|
workspace_abs_path: ({ rel }) => `${root}\\${rel.replaceAll("/", "\\")}`,
|
|
};
|
|
return Object.assign(handlers, { files: store, folders: dirs, root, name });
|
|
};
|
|
|
|
// The settings file and the tab transfer offers of the desktop host (src-tauri/src/preferences.rs, tab_transfer.rs).
|
|
// `crypto.randomUUID` needs a secure context, which `about:blank` is not.
|
|
const pageId = `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
const channel = typeof BroadcastChannel === "function" ? new BroadcastChannel("runestone-smoke-host") : { postMessage() {} };
|
|
channel.addEventListener?.("message", ({ data }) => { if (!data.target || data.target === pageId) emit(data.event, data.payload); });
|
|
// `target` is a page ID. Without it, every page of the context receives the event, this page too.
|
|
const broadcast = (event, payload, target) => {
|
|
if (!target || target === pageId) emit(event, payload);
|
|
if (target !== pageId) channel.postMessage({ event, payload, target });
|
|
};
|
|
const SETTINGS_FILE = "runestone.smoke.settings-file", TRANSFERS = "runestone.smoke.tab-transfers";
|
|
const SECTIONS = ["general", "appearance", "customThemes", "customThemesLegacy", "language"];
|
|
const readJson = (key, fallback) => { try { return JSON.parse(localStorage.getItem(key)) ?? fallback; } catch { return fallback; } };
|
|
const settingsFile = () => readJson(SETTINGS_FILE, null);
|
|
const snapshot = () => {
|
|
const file = settingsFile();
|
|
return { exists: !!file, revision: file?.revision ?? 0, sections: Object.fromEntries(SECTIONS.filter(name => file && name in file).map(name => [name, file[name]])) };
|
|
};
|
|
const writeSettings = (section, value) => {
|
|
if (!SECTIONS.includes(section)) throw `Unknown settings section: ${section}`;
|
|
const file = settingsFile() ?? { schema: 1, revision: 0 };
|
|
file.revision += 1;
|
|
if (value === null || value === undefined) delete file[section]; else file[section] = value;
|
|
localStorage.setItem(SETTINGS_FILE, JSON.stringify(file));
|
|
const change = { section, revision: file.revision, value: value ?? null };
|
|
broadcast("settings-changed", change);
|
|
return change;
|
|
};
|
|
const offers = () => {
|
|
const list = readJson(TRANSFERS, {});
|
|
for (const [id, offer] of Object.entries(list)) if (Date.now() - offer.created >= (offer.taker ? 240000 : 120000)) delete list[id];
|
|
return list;
|
|
};
|
|
const saveOffers = list => localStorage.setItem(TRANSFERS, JSON.stringify(list));
|
|
const expired = "This tab transfer expired. Drag the tab again.";
|
|
const defaults = {
|
|
settings_read: () => snapshot(),
|
|
settings_migrate: ({ sections }) => {
|
|
if (!settingsFile()) localStorage.setItem(SETTINGS_FILE, JSON.stringify({ schema: 1, revision: 1, ...sections }));
|
|
return snapshot();
|
|
},
|
|
settings_write: ({ section, value }) => writeSettings(section, value),
|
|
tab_transfer_offer: ({ id, root, payload }) => {
|
|
const list = offers();
|
|
if (list[id]) throw "Invalid tab transfer.";
|
|
list[id] = { source: pageId, root, payload, created: Date.now(), taker: null };
|
|
saveOffers(list);
|
|
return id;
|
|
},
|
|
tab_transfer_take: ({ id, root }) => {
|
|
const list = offers(), offer = list[id];
|
|
if (!offer || offer.taker) throw expired;
|
|
if (offer.root !== root) throw "Move tabs only between windows of the same workspace.";
|
|
offer.taker = pageId;
|
|
saveOffers(list);
|
|
return offer.payload;
|
|
},
|
|
tab_transfer_finish: ({ id, accepted }) => {
|
|
const list = offers(), offer = list[id];
|
|
if (!offer || offer.taker !== pageId) throw expired;
|
|
if (accepted) delete list[id]; else offer.taker = null;
|
|
saveOffers(list);
|
|
if (accepted) broadcast("tab-transfer-accepted", { id }, offer.source);
|
|
return null;
|
|
},
|
|
tab_transfer_cancel: ({ id }) => {
|
|
const list = offers();
|
|
if (list[id]?.source === pageId && !list[id].taker) { delete list[id]; saveOffers(list); }
|
|
return null;
|
|
},
|
|
};
|
|
|
|
const test = { state: options.state, calls: [], emit, label: options.label, workspace, settings: section => settingsFile()?.[section], writeSettings };
|
|
// Look up the test's handlers first. A test can return a Proxy, so do not copy its keys.
|
|
const table = commands ? commands(test) || {} : {};
|
|
window.isTauri = true;
|
|
window.__TEST__ = test;
|
|
window.__TAURI_INTERNALS__ = {
|
|
metadata: { currentWindow: { label: options.label }, currentWebview: { label: options.label } },
|
|
transformCallback: callback => {
|
|
const id = ++sequence;
|
|
callbacks.set(id, callback);
|
|
return id;
|
|
},
|
|
unregisterCallback: id => callbacks.delete(id),
|
|
invoke: async (command, args = {}) => {
|
|
test.calls.push({ command, args });
|
|
if (command === "plugin:event|listen") {
|
|
const list = listeners.get(args.event) || [];
|
|
list.push(args.handler);
|
|
listeners.set(args.event, list);
|
|
return args.handler;
|
|
}
|
|
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return null; }
|
|
if (command === "plugin:event|emit" || command === "plugin:event|emit_to") { emit(args.event, args.payload); return null; }
|
|
const handler = typeof table[command] === "function" ? table[command] : defaults[command];
|
|
if (typeof handler === "function") {
|
|
const result = await handler(args, test);
|
|
return result === undefined ? null : result;
|
|
}
|
|
if (options.strict) throw new Error(`Unhandled IPC: ${command}`);
|
|
return null;
|
|
},
|
|
};
|
|
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
|
}
|
|
|
|
/**
|
|
* Run one smoke test: start the browser, run `body`, fail on page errors, and close the browser.
|
|
* `body({ browser, page })` returns nothing. Set `allowPageErrors` for tests that expect page errors.
|
|
* On failure, the test saves `failure.png` in its output folder and prints the console errors and warnings.
|
|
*/
|
|
export async function runSmoke(name, body, { viewport, timeout, allowPageErrors = false } = {}) {
|
|
const browser = await launchBrowser();
|
|
let page;
|
|
try {
|
|
page = await openPage(browser, { viewport, timeout });
|
|
await body({ browser, page });
|
|
if (!allowPageErrors && page.errors.length) throw new Error(`Page errors:\n${page.errors.join("\n")}`);
|
|
if (cspViolations.length) throw new Error(`Content security policy violations:\n${[...new Set(cspViolations)].join("\n")}`);
|
|
console.log(`PASS ${name}`);
|
|
} catch (error) {
|
|
console.error(`FAIL ${name}`);
|
|
console.error(error);
|
|
if (cspViolations.length && !String(error?.message).startsWith("Content security policy violations")) {
|
|
console.error(`Content security policy violations:\n${[...new Set(cspViolations)].join("\n")}`);
|
|
}
|
|
if (page) {
|
|
if (page.console.length) console.error(`Console:\n${page.console.join("\n")}`);
|
|
const file = path.join(await outputDir(name), "failure.png");
|
|
if (await page.screenshot({ path: file }).then(() => true, () => false)) console.error(`Screenshot: ${file}`);
|
|
}
|
|
process.exitCode = 1;
|
|
} finally {
|
|
await browser.close();
|
|
}
|
|
}
|