"use strict"; const assert = require("node:assert/strict"); const { spawn } = require("node:child_process"); const { createHash } = require("node:crypto"); const fs = require("node:fs/promises"); const path = require("node:path"); const { setTimeout: delay } = require("node:timers/promises"); const { pathToFileURL } = require("node:url"); const { chromium } = require("playwright"); const [work, executable, ...entryArgs] = process.argv.slice(2); const digest = (bytes) => createHash("sha256").update(bytes).digest("hex"); function startReader(source) { const child = spawn(executable, [...entryArgs, source, "--port", "0", "--no-open"], { detached: true }); const closed = new Promise((resolve) => child.once("close", resolve)); const address = new Promise((resolve, reject) => { let output = ""; const timer = setTimeout(() => reject(new Error("View did not print a loopback address")), 10000); function read(chunk) { output += chunk; const match = output.match(/http:\/\/127\.0\.0\.1:[0-9]+\//); if (match) { clearTimeout(timer); resolve(match[0]); } } child.stdout.on("data", read); child.stderr.on("data", read); child.on("error", (error) => { clearTimeout(timer); reject(error); }); child.on("exit", (code) => { clearTimeout(timer); reject(new Error(`View quit (${code}): ${output}`)); }); }); return { child, address, closed }; } async function stopReader({ child, closed }) { if (!child.pid) return; try { // Core Tool dispatch starts View as a child in the same group. process.kill(-child.pid, "SIGTERM"); } catch (error) { if (error.code !== "ESRCH") throw error; return; } await closed; } async function compareReading(browser, name) { const source = path.join(work, "project", name); const bundle = path.join(work, name); const manifest = JSON.parse(await fs.readFile(path.join(bundle, "manifest.json"))); assert.equal(manifest.mode, "embedded"); assert.equal(manifest.theme, "dark"); assert.equal(manifest.executed, false); assert.equal(manifest.requires.api_revision, 1); assert.equal(manifest.pages.length, 1); assert.equal(manifest.pages[0].source_sha256, digest(await fs.readFile(source))); assert.equal(manifest.pages[0].source_status, name === "plain.md" ? "markdown-only" : "static-ok"); assert.equal(manifest.entry.href, "index.html#detail"); assert.ok(manifest.entry.heading_ids.includes("detail")); assert.equal(manifest.files.filter((file) => file.mime === "image/png").length, 1); for (const file of [...manifest.files, ...manifest.assets]) { assert.equal(digest(await fs.readFile(path.join(bundle, file.path))), file.sha256); assert.ok(!file.path.endsWith(".js")); } const standalone = await browser.newPage({ viewport: { width: 390, height: 600 } }); const reader = startReader(source); let standaloneStyle; try { await standalone.goto(await reader.address); await standalone.locator('[data-action="settings"]').click(); await standalone.locator('[data-action="theme"]').click(); standaloneStyle = await style(standalone.locator(".mq-document")); assert.equal(await standalone.locator(".mq-document img").count(), 1); } finally { await stopReader(reader); await standalone.close(); } const offline = await browser.newContext({ offline: true, viewport: { width: 390, height: 720 } }); try { const page = await offline.newPage(); const requests = []; const errors = []; page.on("request", (request) => requests.push(request.url())); page.on("pageerror", (error) => errors.push(String(error))); const host = path.join(work, "host.html"); await fs.writeFile(host, ``); await page.goto(pathToFileURL(host).href); const frame = page.frameLocator("iframe"); const article = frame.locator(".mq-document"); assert.deepEqual(await style(article), standaloneStyle); assert.equal(await article.locator("math").count(), 1); assert.equal(await article.locator("blockquote").count(), 1); assert.equal(await article.locator("img").count(), 1); assert.equal(await article.locator("img").evaluate((image) => image.naturalWidth), 1); assert.equal(await frame.locator("script,button,.mq-topbar,.mq-dock").count(), 0); assert.equal(await article.getByRole("link").count(), 1); assert.equal(await frame.locator(":target").getAttribute("id"), "detail"); for (const selector of [".mq-table-wrap", ".mq-codeblock pre"]) { const scroller = article.locator(selector); assert.ok(await scroller.evaluate((node) => node.scrollWidth > node.clientWidth)); await scroller.focus(); await scroller.press("ArrowRight"); let scrolled = false; for (let attempt = 0; attempt < 20 && !scrolled; attempt += 1) { await delay(25); scrolled = await scroller.evaluate((node) => node === document.activeElement && node.scrollLeft > 0); } assert.ok(scrolled, `${selector} did not scroll using the keyboard`); } assert.ok(requests.every((url) => url.startsWith("file:") || url.startsWith("data:")), requests); assert.deepEqual(errors, []); } finally { await offline.close(); } } function style(article) { return article.evaluate(async (element) => { await document.fonts.ready; const style = getComputedStyle(element); return { family: style.fontFamily, color: style.color, size: style.fontSize, scheme: style.colorScheme, mathFont: [...document.fonts].find((font) => font.family === "Noto Sans Math")?.status, stylesheet: document.querySelector('link[rel="stylesheet"]').href.split("/").pop(), }; }); } (async () => { const browser = await chromium.launch(); try { for (const name of ["index.mq.md", "plain.md"]) { await compareReading(browser, name); } console.log("Embedded reader: PASS (standalone and sandboxed offline frame, theme, font, anchor, media, keyboard)"); } finally { await browser.close(); } })().catch((error) => { console.error(error); process.exitCode = 1; });