Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/mockup/__tests__/mockup.test.ts

Raw
import assert from "node:assert";
import { request as httpRequest } from "node:http";
import { describe, it } from "vitest";
import {
	MOCKUP_FULL_DOCUMENT_ERROR,
	type MockupRequest,
	renderMockupPage,
	renderPreviewPage,
	startMockupServer,
	validateMockupRequest,
} from "../mockup.ts";
import { openerCandidates } from "../src/pi-ext-browser-open.ts";

const client = {
	userAgent: "mockup-test-browser/1",
	viewport: { width: 1280, height: 720, devicePixelRatio: 1 },
};

const baseRequest: MockupRequest = {
	title: "Pick layout",
	question: "Which option works?",
	options: [
		{
			id: "a",
			label: "A",
			description: "First direction",
			html: "<section><h3>A</h3><script>window.allowed = true;</script></section>",
		},
	],
};

const flowRequest: MockupRequest = {
	title: "Pick flow",
	question: "Which flow works?",
	options: [
		{
			id: "flow",
			label: "Flow",
			pages: [
				{ id: "home", label: "home", html: "<section>home</section>" },
				{
					id: "detail",
					label: "Detail view",
					html: "<section>detail</section>",
				},
			],
		},
		{ id: "single", label: "Single", html: "<section>one</section>" },
	],
};

describe("mockup validation", () => {
	it("rejects full HTML documents with an agent-facing fix", () => {
		for (const html of [
			"<!doctype html><html></html>",
			"<!-- built elsewhere --><html><body>full</body></html>",
		]) {
			assert.throws(
				() =>
					validateMockupRequest({
						...baseRequest,
						options: [{ id: "full", label: "Full", html }],
					}),
				(error) => {
					assert.ok(error instanceof Error);
					assert.strictEqual(
						error.message,
						MOCKUP_FULL_DOCUMENT_ERROR("options[0].html"),
					);
					return true;
				},
			);
		}
	});

	it("allows scripts and styles inside HTML fragments", () => {
		const request = validateMockupRequest({
			...baseRequest,
			options: [
				{
					...baseRequest.options[0],
					html: '<section><style>.x::before{content:"<html"}</style><script>const tag = "<body";</script></section>',
				},
			],
		});
		assert.match(
			request.options[0]!.html ?? "",
			/<style>\.x::before\{content:"<html"\}<\/style>/,
		);
		assert.match(
			request.options[0]!.html ?? "",
			/<script>const tag = "<body";<\/script>/,
		);
	});

	it("rejects parameters outside the minimal public schema", () => {
		assert.throws(
			() => validateMockupRequest({ ...baseRequest, timeout_ms: 1000 }),
			/timeout_ms is not a supported mockup parameter/,
		);
	});

	it("requires either html or pages per option", () => {
		const pages = [
			{ id: "p1", html: "<p>1</p>" },
			{ id: "p2", html: "<p>2</p>" },
		];
		assert.throws(
			() =>
				validateMockupRequest({
					...baseRequest,
					options: [{ id: "a", label: "A", html: "<p>x</p>", pages }],
				}),
			/options\[0\] must provide either html for a single screen or pages for a navigable flow, not both/,
		);
		assert.throws(
			() =>
				validateMockupRequest({
					...baseRequest,
					options: [{ id: "a", label: "A" }],
				}),
			/options\[0\] must provide either html for a single screen or pages for a navigable flow, not neither/,
		);
	});

	it("bounds flow page counts", () => {
		const page = (id: string) => ({ id, html: `<p>${id}</p>` });
		assert.throws(
			() =>
				validateMockupRequest({
					...baseRequest,
					options: [{ id: "a", label: "A", pages: [page("p1")] }],
				}),
			/options\[0\]\.pages must contain at least two pages; use html for a single screen/,
		);
		assert.throws(
			() =>
				validateMockupRequest({
					...baseRequest,
					options: [
						{
							id: "a",
							label: "A",
							pages: Array.from({ length: 13 }, (_, i) => page(`p${i}`)),
						},
					],
				}),
			/options\[0\]\.pages must contain at most twelve items/,
		);
	});

	it("rejects malformed page definitions", () => {
		const flowOption = (pages: unknown) => ({
			...baseRequest,
			options: [{ id: "a", label: "A", pages }],
		});
		assert.throws(
			() => validateMockupRequest(flowOption("nope")),
			/options\[0\]\.pages must be an array/,
		);
		assert.throws(
			() =>
				validateMockupRequest(
					flowOption([
						{ id: "p1", html: "<p>1</p>" },
						{ id: "p1", html: "<p>dup</p>" },
					]),
				),
			/options\[0\]\.pages\[1\]\.id duplicates a previous page id/,
		);
		assert.throws(
			() =>
				validateMockupRequest(
					flowOption([
						{ id: "bad id!", html: "<p>1</p>" },
						{ id: "p2", html: "<p>2</p>" },
					]),
				),
			/options\[0\]\.pages\[0\]\.id must contain only letters, numbers, dot, underscore, or dash/,
		);
		assert.throws(
			() =>
				validateMockupRequest(
					flowOption([
						{ id: "p1", html: "<!doctype html><html></html>" },
						{ id: "p2", html: "<p>2</p>" },
					]),
				),
			(error) => {
				assert.ok(error instanceof Error);
				assert.strictEqual(
					error.message,
					MOCKUP_FULL_DOCUMENT_ERROR("options[0].pages[0].html"),
				);
				return true;
			},
		);
		assert.throws(
			() =>
				validateMockupRequest(
					flowOption([
						{ id: "p1", html: "   " },
						{ id: "p2", html: "<p>2</p>" },
					]),
				),
			/options\[0\]\.pages\[0\]\.html must not be empty/,
		);
		assert.throws(
			() =>
				validateMockupRequest({
					...baseRequest,
					options: [{ id: "a", label: "A", html: "<p>x</p>", page: "home" }],
				}),
			/page is not a supported mockup parameter/,
		);
	});

	it("defaults page labels to the page id", () => {
		const request = validateMockupRequest({
			...baseRequest,
			options: [
				{
					id: "a",
					label: "A",
					pages: [
						{ id: "home", html: "<p>home</p>" },
						{ id: "detail", label: "  ", html: "<p>detail</p>" },
					],
				},
			],
		});
		assert.deepStrictEqual(request.options[0]!.pages, [
			{ id: "home", label: "home", html: "<p>home</p>" },
			{ id: "detail", label: "detail", html: "<p>detail</p>" },
		]);
	});
});

describe("mockup page", () => {
	it("renders fragments inside selectable cards with checkbox controls", () => {
		const html = renderMockupPage(baseRequest, "tok");
		assert.match(html, /type="checkbox"/);
		assert.match(html, /data-option-id="a"/);
		assert.match(
			html,
			/\\u003csection>\\u003ch3>A\\u003c\/h3>\\u003cscript>window\.allowed = true;\\u003c\/script>\\u003c\/section>/,
		);
		assert.match(html, /Pin note/);
		assert.match(html, /pin-bubble/);
		assert.match(html, /Delete pin/);
	});

	it("keeps fragment styles inert until shadow rendering", () => {
		const html = renderMockupPage(
			{
				...baseRequest,
				options: [
					{
						id: "bleed",
						label: "Bleed",
						html: "<style>.panel{position:absolute}</style><section>Card</section>",
					},
				],
			},
			"tok",
		);
		const fragmentMarkup = html.slice(
			html.indexOf('<div class="fragment"'),
			html.indexOf('<section class="drawer"'),
		);
		assert.match(fragmentMarkup, /data-fragment-content/);
		assert.match(
			fragmentMarkup,
			/<script type="application\/json" data-fragment-html>/,
		);
		assert.doesNotMatch(fragmentMarkup, /<style>\.panel\{position:absolute/);
		assert.match(fragmentMarkup, /\\u003cstyle>\.panel\{position:absolute/);
	});

	it("shows global notes and annotations as responsive split panes", () => {
		const html = renderMockupPage(baseRequest, "tok");
		const topbar = html.slice(
			html.indexOf('<header class="topbar">'),
			html.indexOf('<main class="stage"'),
		);
		const drawer = html.slice(
			html.indexOf('<section class="drawer"'),
			html.indexOf("<script>window.__MOCKUP_TOKEN__"),
		);
		assert.doesNotMatch(topbar, /id="iterate"|id="accept"/);
		assert.match(drawer, /id="iterate"/);
		assert.match(drawer, /id="accept"/);
		assert.doesNotMatch(drawer, /role="tablist"|data-tab=/);
		assert.ok(
			drawer.indexOf('id="global-notes"') <
				drawer.indexOf('id="annotations-panel"'),
		);
		assert.match(html, /\.feedback-grid \{[^}]*grid-template-columns:minmax/);
		assert.match(html, /@media \(max-width:720px\)/);
		assert.match(html, /\.feedback-grid \{ grid-template-columns:1fr; \}/);
	});

	it("shows one-shot pin mode with cursor and toggle state", () => {
		const html = renderMockupPage(baseRequest, "tok");
		assert.match(
			html,
			/\.option-card\.pin-armed \.fragment \{[^}]*cursor:crosshair/,
		);
		assert.match(html, /card\.classList\.toggle\("pin-armed", armed === id\)/);
		assert.match(
			html,
			/pin\.textContent = armed === id \? "Pinning…" : "Pin note"/,
		);
		assert.match(html, /armed = null;\n {2}sync\(\);\n {2}showBubble/);
	});

	it("selects label-backed options only once", () => {
		const html = renderMockupPage(baseRequest, "tok");
		assert.match(html, /\$\("input", card\)\.addEventListener\("change"/);
		assert.match(html, /closest\("label,button"\)/);
	});

	it("places pins relative to scrolled fragment content", () => {
		const html = renderMockupPage(baseRequest, "tok");
		assert.match(
			html,
			/\(event\.clientX - rect\.left \+ frag\.scrollLeft\) \/ frag\.scrollWidth/,
		);
		assert.match(
			html,
			/\(event\.clientY - rect\.top \+ frag\.scrollTop\) \/ frag\.scrollHeight/,
		);
	});

	it("renders flow payloads as escaped JSON page manifests", () => {
		const html = renderMockupPage(flowRequest, "tok");
		const payload =
			html.match(
				/<script type="application\/json" data-fragment-html>([\s\S]*?)<\/script>/,
			)![1] ?? "";
		assert.match(payload, /\\u003csection>/);
		assert.deepStrictEqual(JSON.parse(payload), {
			pages: [
				{ id: "home", label: "home", html: "<section>home</section>" },
				{
					id: "detail",
					label: "Detail view",
					html: "<section>detail</section>",
				},
			],
		});
	});

	it("renders a static preview page per option", () => {
		const html = renderPreviewPage(flowRequest);
		const hosts = html.match(
			/<div class="preview-host" data-preview-option="/g,
		);
		assert.strictEqual(hosts?.length ?? 0, 2);
		assert.match(html, /data-preview-option="flow"/);
		assert.match(html, /data-preview-option="single"/);
		assert.doesNotMatch(html, /EventSource/);
		assert.doesNotMatch(html, /\/api\//);
	});
});

describe("mockup browser opener", () => {
	it("uses the native URL handler directly on win32 without cmd", () => {
		assert.deepStrictEqual(
			openerCandidates("http://127.0.0.1:1", {
				platform: "win32",
				env: {},
			})[0],
			{
				command: "rundll32.exe",
				args: ["url.dll,FileProtocolHandler", "http://127.0.0.1:1"],
				windowsHide: true,
			},
		);
	});
});

describe("mockup server", () => {
	it("rejects multiple submitted selections unless multi is enabled", async () => {
		const server = await startMockupServer(
			{
				...baseRequest,
				options: [
					...baseRequest.options,
					{ id: "b", label: "B", html: "<section>B</section>" },
				],
			},
			{ openBrowser: false },
		);
		try {
			const res = await fetch(new URL("/api/submit", server.url), {
				method: "POST",
				headers: {
					Authorization: `Bearer ${server.token}`,
					"Content-Type": "application/json",
				},
				body: JSON.stringify({
					action: "accept",
					selected: ["a", "b"],
					notes: "",
					annotations: [],
					client,
				}),
			});
			assert.strictEqual(res.status, 400);
			assert.match(await res.text(), /selected must contain at most one item/);
		} finally {
			server.result.catch(() => undefined);
			server.close("test");
		}
	});

	it("preserves UTF-8 split across request chunks", async () => {
		const server = await startMockupServer(baseRequest, { openBrowser: false });
		try {
			const body = Buffer.from(
				JSON.stringify({
					action: "accept",
					selected: ["a"],
					notes: "before 😀 after",
					annotations: [],
					client,
				}),
			);
			const split = body.indexOf(Buffer.from("😀")) + 1;
			await new Promise<void>((resolve, reject) => {
				const url = new URL("/api/submit", server.url);
				const req = httpRequest(
					url,
					{
						method: "POST",
						headers: {
							Authorization: `Bearer ${server.token}`,
							"Content-Type": "application/json",
						},
					},
					(res) => {
						res.resume();
						res.once("end", resolve);
					},
				);
				req.once("error", reject);
				req.write(body.subarray(0, split));
				setImmediate(() => req.end(body.subarray(split)));
			});
			assert.strictEqual((await server.result).notes, "before 😀 after");
		} finally {
			server.result.catch(() => undefined);
			server.close("test");
		}
	});

	it("blocks until browser submits action, selection, notes, and annotations", async () => {
		const server = await startMockupServer(baseRequest, { openBrowser: false });
		try {
			assert.match(server.url, /[?&]k=/);
			assert.doesNotMatch(server.url, /token=|key=/);
			const posted = fetch(new URL("/api/submit", server.url), {
				method: "POST",
				headers: {
					Authorization: `Bearer ${server.token}`,
					"Content-Type": "application/json",
				},
				body: JSON.stringify({
					action: "iterate",
					selected: ["a"],
					notes: "keep A, denser drawer",
					annotations: [{ optionId: "a", x: 0.25, y: 0.5, note: "tighten" }],
					client,
				}),
			});
			const res = await posted;
			assert.strictEqual(await res.text(), '{"ok":true}');
			const result = await server.result;
			assert.deepStrictEqual(
				{
					action: result.action,
					selected: result.selected,
					notes: result.notes,
					annotations: result.annotations,
					userAgent: result.review.userAgent,
					viewport: result.review.viewport,
				},
				{
					action: "iterate",
					selected: ["a"],
					notes: "keep A, denser drawer",
					annotations: [{ optionId: "a", x: 0.25, y: 0.5, note: "tighten" }],
					userAgent: client.userAgent,
					viewport: client.viewport,
				},
			);
			assert.match(result.review.submittedAt, /^\d{4}-\d{2}-\d{2}T/);
		} finally {
			server.result.catch(() => undefined);
			server.close("test");
		}
	});

	it("validates annotation pages against flow options", async () => {
		const server = await startMockupServer(flowRequest, { openBrowser: false });
		const submit = (annotations: unknown[]) =>
			fetch(new URL("/api/submit", server.url), {
				method: "POST",
				headers: {
					Authorization: `Bearer ${server.token}`,
					"Content-Type": "application/json",
				},
				body: JSON.stringify({
					action: "iterate",
					selected: ["flow"],
					notes: "",
					annotations,
					client,
				}),
			});
		try {
			let res = await submit([
				{ optionId: "flow", x: 0.5, y: 0.5, note: "no page" },
			]);
			assert.strictEqual(res.status, 400);
			assert.match(await res.text(), /annotations\[0\]\.page must be a string/);
			res = await submit([
				{ optionId: "flow", page: "nope", x: 0.5, y: 0.5, note: "bad page" },
			]);
			assert.strictEqual(res.status, 400);
			assert.match(
				await res.text(),
				/annotations\[0\]\.page must match a page id/,
			);
			res = await submit([
				{
					optionId: "single",
					page: "home",
					x: 0.5,
					y: 0.5,
					note: "stray page",
				},
			]);
			assert.strictEqual(res.status, 400);
			assert.match(
				await res.text(),
				/annotations\[0\]\.page is only valid for options with pages/,
			);
			res = await submit([
				{ optionId: "flow", page: "detail", x: 0.5, y: 0.5, note: "ok" },
			]);
			assert.strictEqual(res.status, 200);
			const result = await server.result;
			assert.deepStrictEqual(result.annotations, [
				{ optionId: "flow", page: "detail", x: 0.5, y: 0.5, note: "ok" },
			]);
		} finally {
			server.result.catch(() => undefined);
			server.close("test");
		}
	});

	it("keeps one URL across iterations and accepts no selection", async () => {
		const server = await startMockupServer(baseRequest, { openBrowser: false });
		try {
			const first = server.result;
			const firstResponse = await fetch(new URL("/api/submit", server.url), {
				method: "POST",
				headers: {
					Authorization: `Bearer ${server.token}`,
					"Content-Type": "application/json",
				},
				body: JSON.stringify({
					action: "iterate",
					selected: ["a"],
					notes: "try again",
					annotations: [],
					client,
				}),
			});
			assert.strictEqual(firstResponse.status, 200);
			assert.strictEqual((await first).action, "iterate");

			const stableUrl = server.url;
			const second = server.present({
				...baseRequest,
				question: "Is this revision right?",
			});
			assert.strictEqual(server.url, stableUrl);
			const page = await fetch(server.url);
			assert.match(await page.text(), /Is this revision right\?/);
			const secondResponse = await fetch(new URL("/api/submit", server.url), {
				method: "POST",
				headers: {
					Authorization: `Bearer ${server.token}`,
					"Content-Type": "application/json",
				},
				body: JSON.stringify({
					action: "accept",
					selected: [],
					notes: "none works",
					annotations: [],
					client,
				}),
			});
			assert.strictEqual(secondResponse.status, 200);
			assert.deepStrictEqual((await second).selected, []);
		} finally {
			server.result.catch(() => undefined);
			server.close("test");
		}
	});

	it("authenticates browser requests that stop active Pi work", async () => {
		let aborts = 0;
		const server = await startMockupServer(baseRequest, {
			openBrowser: false,
			abortAgent: () => {
				aborts++;
				return true;
			},
		});
		try {
			const unauthorized = await fetch(new URL("/api/abort", server.url), {
				method: "POST",
			});
			assert.strictEqual(unauthorized.status, 401);
			const stopped = await fetch(new URL("/api/abort", server.url), {
				method: "POST",
				headers: { Authorization: `Bearer ${server.token}` },
			});
			assert.strictEqual(stopped.status, 200);
			assert.strictEqual(aborts, 1);
		} finally {
			server.result.catch(() => undefined);
			server.close("test");
		}
	});
});