Files

68 lines
3.0 KiB
JavaScript

// Renders the plugin's slot in jsdom with a fake bridge (`window.aiAgentPlugin`):
// `query("checks", payload)` answers from the fixtures file by
// `payload.conversationId || payload.sessionId` (a missing key: `{found: false}`),
// `refresh()` is recorded and answers again. Then plays the steps —
// `{"event": {type, id?, ids?}}`, `{"update": {…}}`, `{"wait": ms}`,
// `{"fixture": {key: answer}}` (changes what the next read gets) — and prints
// {checks, text, calls, errors, empty, heights} as JSON. Test-only.
//
// NODE_PATH=<a node_modules with jsdom> node render_harness.js <slot.html> <fixtures.json> '<init json>' '<steps json>'
"use strict";
const fs = require("fs");
const { JSDOM } = require("jsdom");
const html = fs.readFileSync(process.argv[2], "utf8");
const fixtures = JSON.parse(fs.readFileSync(process.argv[3], "utf8"));
const init = JSON.parse(process.argv[4] || "{}");
const steps = JSON.parse(process.argv[5] || "[]");
const calls = [], errors = [], heights = [];
let empty = null, onEvent = null, onUpdate = null;
const dom = new JSDOM(html, { runScripts: "outside-only", pretendToBeVisual: true, url: "https://plugin.invalid/" });
const w = dom.window;
w.console.error = (...a) => errors.push(a.join(" "));
w.addEventListener("error", (e) => errors.push(String(e.message)));
const answer = (p) => {
const d = fixtures[p.conversationId || p.sessionId];
return d === undefined ? { found: false } : d;
};
w.aiAgentPlugin = {
init: Object.assign({ theme: { scheme: "light", tokens: {} } }, init),
query(name, payload, cb) {
calls.push(["query", name, payload]);
setTimeout(() => cb(answer(payload), { fetching: false }), 0);
return {
stop() {},
refresh() { calls.push(["refresh", name]); setTimeout(() => cb(answer(payload), { fetching: false }), 0); return Promise.resolve(); },
};
},
action(name, payload) { calls.push(["action", name, payload]); return Promise.resolve(answer(payload)); },
onUpdate(cb) { onUpdate = cb; if (init.update) cb(init.update); },
onEvent(cb) { onEvent = cb; },
resize(h) { heights.push(h); },
setEmpty(e) { empty = e; },
};
for (const m of html.matchAll(/<script>([\s\S]*?)<\/script>/g)) {
try { w.eval(m[1]); } catch (e) { errors.push(String((e && e.stack) || e)); }
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
(async () => {
await sleep(20);
for (const s of steps) {
if (s.wait) await sleep(s.wait);
if (s.event && onEvent) onEvent(s.event);
if (s.update && onUpdate) onUpdate(s.update);
if (s.fixture) Object.assign(fixtures, s.fixture);
}
await sleep(20);
const checks = [...w.document.querySelectorAll("[data-check]")].map((n) => ({
key: n.getAttribute("data-check"), lit: n.classList.contains("lit"), title: n.getAttribute("title"),
}));
const group = w.document.querySelector("[role=group]");
process.stdout.write(JSON.stringify({
checks, label: group && group.getAttribute("aria-label"), calls, errors, empty, heights,
}));
w.close();
process.exit(0);
})();