diff --git a/CLAUDE.md b/CLAUDE.md index 98fb469..1a2b160 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -20,7 +20,8 @@ scripts the release's version check. Releases (notes, screenshots): docs cargo test --workspace # quote test counts per crate; an exit code alone is not green cargo run -p ianitor-control -- --dev pnpm --filter web dev # 127.0.0.1 only, never --host -node apps/web/scripts/shots.mjs # the release's screenshots (demo data, headless Edge) -> target/aula (docs/release.md) +pnpm --filter web test:e2e # the web UI's flows in Edge on demo data, recorded -> target/e2e/videos (docs/fabrica.md) +pnpm --filter web aula:shots # the Aula screenshots from the same suite -> target/e2e/aula; then `fabrica aula shots` node scripts/check-version.mjs X.Y.Z # Cargo.toml and both package.json carry the version nix build .#ianitor nix flake check # includes NixOS VM tests (Linux + KVM) diff --git a/apps/web/e2e/clock.ts b/apps/web/e2e/clock.ts new file mode 100644 index 0000000..f5703a2 --- /dev/null +++ b/apps/web/e2e/clock.ts @@ -0,0 +1,6 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +/** The suite's instant: the demo's answers and the page's Date both read it (a Monday morning in Prague). */ +export const CLOCK = "2026-11-16T09:30:00+01:00"; diff --git a/apps/web/e2e/fixtures.ts b/apps/web/e2e/fixtures.ts new file mode 100644 index 0000000..8f0277f --- /dev/null +++ b/apps/web/e2e/fixtures.ts @@ -0,0 +1,64 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// What every e2e test gets: the demo started over, the page's clock at the suite's instant, `open` +// for a page of the UI, and afterwards a check that nothing the page showed looks real +// (tests/demo.ts realLooking: names outside .test, addresses outside the documentation ranges). +// A test with a `video` annotation has its recording kept as target/e2e/videos/.webm. + +import { mkdirSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { test as base, expect, type Page } from "@playwright/test"; +import { realLooking } from "../tests/demo"; +import { CLOCK } from "./clock"; + +export const REPO = resolve(fileURLToPath(new URL(".", import.meta.url)), "../../.."); +export const TARGET = join(REPO, "target", "e2e"); + +function url(): string { + const u = process.env.IANITOR_E2E_URL; + if (!u) throw new Error("IANITOR_E2E_URL is not set: run the suite through playwright.config.ts (its global setup serves the demo)"); + return u; +} + +/** Every text, field value and link the page shows (the body: the head's links are the build's own files). */ +async function shown(page: Page): Promise { + return page.evaluate(() => { + const out: string[] = []; + const walk = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT); + for (let n = walk.nextNode(); n; n = walk.nextNode()) if (n.textContent?.trim()) out.push(n.textContent); + document.body.querySelectorAll("input, textarea").forEach((i) => out.push(i.value)); + document.body.querySelectorAll("[href]").forEach((a) => out.push(a.getAttribute("href") ?? "")); + return out; + }); +} + +export const test = base.extend<{ open: (path: string) => Promise }>({ + open: async ({ page, request }, use) => { + const res = await request.post(`${url()}/__demo/reset`); + expect(res.status()).toBe(204); + await page.clock.setFixedTime(new Date(CLOCK)); + await use(async (path: string) => { + await page.goto(url() + path); + }); + }, +}); + +test.afterEach(async ({ page }, info) => { + const video = info.annotations.find((a) => a.type === "video")?.description; + if (!page.isClosed()) { + const seen = (await shown(page)).flatMap(realLooking); + expect(seen, "the page showed something that looks real").toEqual([]); + } + const rec = page.video(); + if (video && rec && info.status === info.expectedStatus) { + await page.close(); + const dir = join(TARGET, "videos"); + mkdirSync(dir, { recursive: true }); + await rec.saveAs(join(dir, `${video}.webm`)); + } +}); + +export { expect }; diff --git a/apps/web/e2e/serve.ts b/apps/web/e2e/serve.ts new file mode 100644 index 0000000..861e215 --- /dev/null +++ b/apps/web/e2e/serve.ts @@ -0,0 +1,113 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// The e2e suite's server (Playwright's global setup): builds the web UI (Vite, production) into a +// fresh temporary folder and serves it on 127.0.0.1 at a free port, with /api/v1 answered by the +// demo control plane (tests/demo.ts) at the suite's fixed instant. Any other path falls back to +// index.html, as in production. POST /__demo/reset starts the demo over (each test starts from the +// same invented server). The address reaches the tests as IANITOR_E2E_URL. Nothing here listens on +// anything but loopback, and the temporary folder is removed when the run ends. + +import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs"; +import { createServer, type IncomingMessage, type Server } from "node:http"; +import { tmpdir } from "node:os"; +import { extname, join, normalize, resolve, sep } from "node:path"; +import { fileURLToPath } from "node:url"; +import { build } from "vite"; +import { demoApi } from "../tests/demo"; +import { clock } from "../tests/mockApi"; +import { CLOCK } from "./clock"; + +const web = resolve(fileURLToPath(new URL(".", import.meta.url)), ".."); + +const TYPES: Record = { + ".html": "text/html; charset=utf-8", + ".js": "text/javascript; charset=utf-8", + ".css": "text/css; charset=utf-8", + ".json": "application/json", + ".svg": "image/svg+xml", + ".png": "image/png", + ".ico": "image/x-icon", + ".woff": "font/woff", + ".woff2": "font/woff2", + ".txt": "text/plain; charset=utf-8", +}; + +function body(req: IncomingMessage): Promise> { + return new Promise((ok) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + try { + ok(chunks.length ? (JSON.parse(Buffer.concat(chunks).toString("utf8")) as Record) : {}); + } catch { + ok({}); + } + }); + }); +} + +function serve(dist: string): Promise { + const index = readFileSync(join(dist, "index.html")); + let api = demoApi(); + const server = createServer((req, res) => { + const url = new URL(req.url ?? "/", "http://127.0.0.1"); + if (url.pathname === "/__demo/reset" && req.method === "POST") { + api = demoApi(); + res.writeHead(204).end(); + return; + } + if (url.pathname === "/api/v1" || url.pathname.startsWith("/api/v1/")) { + void body(req).then((b) => { + const a = api(req.method ?? "GET", url.pathname.slice("/api/v1".length) + url.search, b); + res.writeHead(a.status, { "Content-Type": "application/json", "Cache-Control": "no-store" }); + res.end(a.text ?? undefined); + }); + return; + } + let path: string; + try { + path = decodeURIComponent(url.pathname); + } catch { + res.writeHead(400).end(); + return; + } + const file = normalize(join(dist, path)); + if (file.startsWith(dist + sep) && existsSync(file) && statSync(file).isFile()) { + res.writeHead(200, { "Content-Type": TYPES[extname(file)] ?? "application/octet-stream" }); + res.end(readFileSync(file)); + return; + } + res.writeHead(200, { "Content-Type": TYPES[".html"], "Cache-Control": "no-store" }); + res.end(index); + }); + return new Promise((ok, fail) => { + server.once("error", fail); + server.listen(0, "127.0.0.1", () => ok(server)); + }); +} + +export default async function setup(): Promise<() => Promise> { + clock.fixed = Date.parse(CLOCK); + const tmp = mkdtempSync(join(tmpdir(), "ianitor-e2e-")); + const remove = () => rmSync(tmp, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }); + let server: Server; + try { + const dist = join(tmp, "dist"); + await build({ root: web, logLevel: "warn", build: { outDir: dist, emptyOutDir: true } }); + server = await serve(dist); + } catch (e) { + remove(); + throw e; + } + const addr = server.address(); + if (!addr || typeof addr === "string") throw new Error("the demo server has no port"); + process.env.IANITOR_E2E_URL = `http://127.0.0.1:${addr.port}`; + console.log(`e2e: the built UI and the demo control plane on ${process.env.IANITOR_E2E_URL}`); + return async () => { + server.closeAllConnections(); + await new Promise((r) => server.close(() => r())); + remove(); + }; +} diff --git a/apps/web/e2e/specs/aula.spec.ts b/apps/web/e2e/specs/aula.spec.ts new file mode 100644 index 0000000..0aa75f5 --- /dev/null +++ b/apps/web/e2e/specs/aula.spec.ts @@ -0,0 +1,28 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// The release's screenshots (docs/release.md): each shot of tests/demo.ts SHOTS, 1440 × 900 at +// scale 1, saved as target/e2e/aula/.png. .fabrica/aula.yaml lists the same files, which +// `fabrica aula shots` checks and publishes as aula-.png with aula.json. + +import { mkdirSync } from "node:fs"; +import { join } from "node:path"; +import { SHOTS } from "../../tests/demo"; +import { TARGET, expect, test } from "../fixtures"; + +const dir = join(TARGET, "aula"); + +for (const shot of SHOTS) { + test(`aula: ${shot.name}`, async ({ page, open }) => { + await open(shot.path); + for (const sel of shot.click ?? []) await page.locator(sel).first().click(); + await expect(page.locator(shot.wait).first()).toBeAttached(); + // Nothing still loading, the fonts in, two frames drawn and transitions over. + await expect(page.locator("[aria-busy=true]")).toHaveCount(0); + await page.evaluate(() => document.fonts.ready.then(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))))); + await page.waitForTimeout(400); + mkdirSync(dir, { recursive: true }); + await page.screenshot({ path: join(dir, `${shot.name}.png`), animations: "disabled", caret: "hide" }); + }); +} diff --git a/apps/web/e2e/specs/flows.spec.ts b/apps/web/e2e/specs/flows.spec.ts new file mode 100644 index 0000000..08179e5 --- /dev/null +++ b/apps/web/e2e/specs/flows.spec.ts @@ -0,0 +1,116 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// The main flows of ROADMAP §4 in a real browser, on the built UI and the demo control plane, with +// the clicks counted as in the smoke test (tests/flows.test.ts). Each is recorded: the showcase +// videos (docs/fabrica.md part 5) are target/e2e/videos/.webm. + +import type { Locator, Page } from "@playwright/test"; +import { expect, test } from "../fixtures"; + +function counter() { + let n = 0; + return { + click: async (l: Locator) => { + n++; + await l.click(); + }, + get count() { + return n; + }, + }; +} + +/** A beat for the viewer of the video, so a screen is seen before the next click. */ +const beat = (page: Page) => page.waitForTimeout(700); +const nav = (page: Page) => page.getByRole("navigation", { name: "Main" }).first(); + +test("Add a host: + Host → fill → Apply = 2 clicks, kept", { annotation: { type: "video", description: "add-host" } }, async ({ page, open }) => { + const c = counter(); + await open("/"); + await expect(page.getByRole("button", { name: "More for wiki.home.test" })).toBeVisible(); + await beat(page); + await c.click(page.getByRole("button", { name: "Add a host" })); + await page.getByLabel("Hostname").pressSequentially("notes.home.test"); + await page.getByLabel("Send traffic to").fill("http://192.0.2.60:8080"); + await beat(page); + await c.click(page.getByRole("button", { name: "Apply" })); + await expect(page.locator("dialog.ia-panel")).toHaveCount(0, { timeout: 10_000 }); + await expect(page.getByRole("button", { name: "More for notes.home.test" })).toBeVisible(); + await beat(page); + expect(c.count).toBe(2); +}); + +test("Undo the last change = 1 click", { annotation: { type: "video", description: "undo" } }, async ({ page, open }) => { + const c = counter(); + await open("/"); + const undo = page.getByRole("button", { name: /^Undo: Added recipes\.home\.test/ }); + await expect(undo).toBeVisible(); + await beat(page); + const sent = page.waitForRequest((r) => r.method() === "POST" && r.url().endsWith("/api/v1/undo")); + await c.click(undo); + expect((await sent).postDataJSON()).toMatchObject({ target_change_id: "ch_0008" }); + await beat(page); + expect(c.count).toBe(1); +}); + +test("Restore: History → pick → Restore = 3 clicks", { annotation: { type: "video", description: "restore" } }, async ({ page, open }) => { + const c = counter(); + await open("/"); + await expect(page.getByRole("button", { name: "Add a host" })).toBeVisible(); + await c.click(nav(page).getByRole("link", { name: "History" })); + await beat(page); + await c.click(page.getByRole("button", { name: /Turned share links on for wiki\.home\.test/ })); + await expect(page.getByRole("button", { name: "Restore this version" })).toBeVisible(); + await beat(page); + const sent = page.waitForRequest((r) => r.method() === "POST" && r.url().endsWith("/api/v1/restore")); + await c.click(page.getByRole("button", { name: "Restore this version" })); + await sent; + await beat(page); + expect(c.count).toBe(3); +}); + +test("Share link: ⋯ → Share link → Copy = 3 clicks, 7 days", { annotation: { type: "video", description: "share-link" } }, async ({ page, context, open }) => { + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + const c = counter(); + await open("/"); + await c.click(page.getByRole("button", { name: "More for wiki.home.test" })); + const minted = page.waitForRequest((r) => r.method() === "POST" && r.url().endsWith("/share-links")); + await c.click(page.getByRole("menuitem", { name: /Share link/ })); + expect((await minted).postDataJSON()).toMatchObject({ expires_in_s: 604800 }); + const copy = page.getByRole("button", { name: "Copy link" }); + await expect(copy).not.toHaveAttribute("aria-disabled", /.*/); + await beat(page); + await c.click(copy); + await expect(page.getByText("Copied")).toBeVisible(); + await beat(page); + expect(c.count).toBe(3); +}); + +test("Switch engine: engine chip → Switch to Caddy = 2 clicks", { annotation: { type: "video", description: "engine" } }, async ({ page, open }) => { + const c = counter(); + await open("/"); + await c.click(page.getByRole("button", { name: /^Engine: Pingora/ })); + await expect(page.getByRole("button", { name: "Switch to Caddy" })).toBeVisible(); + await beat(page); + await c.click(page.getByRole("button", { name: "Switch to Caddy" })); + await expect(page.getByText("Now serving with Caddy.")).toBeVisible({ timeout: 10_000 }); + await beat(page); + expect(c.count).toBe(2); +}); + +test("Device certificate: Certificates → + Device → Issue = 3 clicks", { annotation: { type: "video", description: "device-certificate" } }, async ({ page, open }) => { + const c = counter(); + await open("/"); + await expect(page.getByRole("button", { name: "Add a host" })).toBeVisible(); + await c.click(nav(page).getByRole("link", { name: "Certificates" })); + await beat(page); + await c.click(page.getByRole("button", { name: "Add a device certificate" })); + await page.getByLabel("Device name").fill("felix's tablet"); + await c.click(page.getByRole("button", { name: "Issue" })); + await expect(page.getByLabel("Match code 47 19 83")).toBeVisible(); + expect(c.count).toBe(3); + await expect(page.getByRole("button", { name: "Show QR code" })).toBeVisible({ timeout: 10_000 }); + await beat(page); +}); diff --git a/apps/web/package.json b/apps/web/package.json index c5adebc..53bf0f2 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,6 +1,6 @@ { "name": "web", - "version": "0.1.0", + "version": "0.2.0", "private": true, "license": "MPL-2.0", "description": "Ianitor Domi web UI (Svelte 5, runes, TypeScript strict). A pure client of the control API.", @@ -10,12 +10,14 @@ "build": "vite build", "check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings", "test": "vitest run", - "shots": "node scripts/shots.mjs" + "test:e2e": "playwright test --project=web", + "aula:shots": "playwright test --project=aula" }, "dependencies": { "@ianitor/ui": "workspace:*" }, "devDependencies": { + "@playwright/test": "1.56.1", "@sveltejs/vite-plugin-svelte": "^5.0.3", "@testing-library/svelte": "^5.2.6", "@testing-library/user-event": "^14.6.1", diff --git a/apps/web/playwright.config.ts b/apps/web/playwright.config.ts new file mode 100644 index 0000000..17fb383 --- /dev/null +++ b/apps/web/playwright.config.ts @@ -0,0 +1,51 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// The web UI's end-to-end suite (docs/fabrica.md, part 5): the built UI in a real browser against +// the demo control plane (tests/demo.ts, invented data only), served on 127.0.0.1 by e2e/serve.ts. +// Two projects: +// web the main flows of ROADMAP §4, each recorded as a video (target/e2e/videos/.webm); +// Fabrica's `web` target (.fabrica/tests.yaml) and its e2e pipeline run this one. +// aula the release's screenshots (target/e2e/aula/.png), which `fabrica aula shots` checks +// and publishes (.fabrica/aula.yaml, `file:` shots). +// Every page is drawn at a fixed instant in a fixed zone, so two takes of a screen are the same. +// On Windows the browser is the installed Edge (PW_CHANNEL names another, e.g. chrome): nothing is +// downloaded. Elsewhere it is Playwright's own Chromium. Videos need Playwright's ffmpeg, which lives +// in PLAYWRIGHT_BROWSERS_PATH (on F: on Mark's PC, never C:). + +import { defineConfig, devices } from "@playwright/test"; + +const channel = process.env.PW_CHANNEL ?? (process.platform === "win32" ? "msedge" : undefined); +// Fabrica's live view (Fabrica docs/20_tests.md part 3): the port its Tests page watches. +const devtools = process.env.FABRICA_TESTS_DEVTOOLS ? [`--remote-debugging-port=${process.env.FABRICA_TESTS_DEVTOOLS}`] : []; + +const desktop = { + ...devices["Desktop Chrome"], + ...(channel ? { channel } : {}), + viewport: { width: 1440, height: 900 }, + deviceScaleFactor: 1, + locale: "en-GB", + timezoneId: "Europe/Prague", + launchOptions: { args: ["--lang=en-GB", ...devtools] }, +}; + +export default defineConfig({ + testDir: "e2e/specs", + outputDir: "../../target/e2e/results", + globalSetup: "./e2e/serve.ts", + fullyParallel: false, + workers: 1, + retries: 0, + forbidOnly: !!process.env.CI, + // Generous: the release PC runs several apps' suites at once, and a loaded PC types and draws slowly + // (one Edge start took 45 s there, one flow 72 s). A real hang still ends. + timeout: 180_000, + expect: { timeout: 15_000 }, + reporter: [["list"]], + use: { trace: "retain-on-failure" }, + projects: [ + { name: "web", testMatch: "flows.spec.ts", use: { ...desktop, video: { mode: "on", size: { width: 1440, height: 900 } } } }, + { name: "aula", testMatch: "aula.spec.ts", use: desktop }, + ], +}); diff --git a/apps/web/tests/demo.test.ts b/apps/web/tests/demo.test.ts index 2abed14..2d7da42 100644 --- a/apps/web/tests/demo.test.ts +++ b/apps/web/tests/demo.test.ts @@ -10,24 +10,7 @@ import { cleanup, render, waitFor } from "@testing-library/svelte"; import { afterEach, describe, expect, it } from "vitest"; import App from "../src/App.svelte"; import { app } from "../src/lib/app.svelte"; -import { SHOTS, demoApi } from "./demo"; - -const ALLOWED_TLDS = new Set(["test", "example", "invalid"]); -const DOC_NETS = ["192.0.2.", "198.51.100.", "203.0.113."]; -const FORBIDDEN = ["mark", "marek", "novak", "flowers", "esp32", "hyperv"]; - -/** What in a text could be real: addresses outside the documentation ranges, names outside .test. */ -function realLooking(text: string): string[] { - const found: string[] = []; - for (const m of text.matchAll(/(? m[0].startsWith(n))) found.push(m[0]); - } - for (const m of text.matchAll(/(?; const DAY = 86_400; -const at = (s: number) => new Date(Date.now() + s * 1000).toISOString(); +const at = (s: number) => new Date(nowMs() + s * 1000).toISOString(); interface Health { state: string; @@ -97,8 +97,8 @@ function intermediate(): Json { return { state: "ok", subject: "Demo Intermediate CA", not_after: at(212 * DAY), days_left: 212, renewal: null, banner: null }; } -function overview(): Json { - const list = hosts(); +function overview(added: Json[] = []): Json { + const list = [...hosts(), ...added]; const count = (s: string) => list.filter((h) => (h.health as Json).state === s).length; return { counts: { hosts: list.length, healthy: count("healthy"), degraded: count("degraded"), down: count("down"), unknown: count("unknown") }, @@ -213,10 +213,47 @@ function certs(): Json { }; } -/** The demo's own answers, first; the smoke test's stand-in answers the rest. */ +/** The demo's own answers, first; the smoke test's stand-in answers the rest. A host added in the + * demo (the e2e suite's Add host flow) is listed from then on, healthy, with the upstream it was + * given; a device certificate request carries the name it was asked with. */ export function demoRoutes(): Route[] { + const m = newMock(); + const added: Json[] = []; + let device = ""; + const request = (state: "waiting" | "approved"): Json => ({ + request_id: "pr_dev", + kind: "device", + state, + match_code: "47 19 83", + created_at: at(-5), + expires_at: at(600), + approved_at: state === "approved" ? at(0) : null, + device_id: state === "approved" ? "dv_1" : null, + name: device, + csr_pem: null, + not_after: state === "approved" ? at(365 * DAY) : null, + message_code: state === "approved" ? "pki.issued" : "pki.waiting.manual", + message: state === "approved" ? `${device} has a certificate.` : "Approve it on the server with the match code.", + approve_command: state === "approved" ? null : "ianitor-control pki approve 47 19 83", + problem: null, + }); return [ - ["GET", /^\/overview$/, () => [200, overview()]], + ["GET", /^\/overview$/, () => [200, overview(added)]], + ["POST", /^\/hosts$/, (_, b) => { + const h = b.host as Json; + const name = String(h.hostname); + m.state.hostsAdded.push(name); + const ups = Array.isArray(h.upstreams) ? h.upstreams.map(String) : []; + added.push(demoHost(name, ups, { state: "healthy", latency: 11 }, { added_at: at(0) })); + return [202, { apply: apply("ch_new", "queued", `Added ${name}`, [name]) }]; + }], + ["POST", /^\/certs\/devices$/, (_, b) => { + device = String(b.name ?? ""); + return [202, request("waiting")]; + }], + ["GET", /^\/pki-requests\/pr_dev$/, () => [200, request("approved")]], + // A share link whose token cannot be read as a name (the stand-in's `ish1.abc` would be). + ["POST", /^\/hosts\/([^/]+)\/share-links$/, (mm) => [201, { id: "sl_demo", url: `https://${decodeURIComponent(mm[1])}/?share=ish1.4f9c2a7e1b0d`, expires_at: at(7 * DAY), path_prefix: "/", has_password: false, warning: null }]], ["GET", /^\/hosts\/([^/?]+)$/, (mm) => { const s = spec(decodeURIComponent(mm[1])); return s ? [200, { host: s, rev: "rev-demo-8" }] : [404, { error: { code: "host.not_found", message: "There is no such host.", field: null, params: {}, retry_after_s: null, detail: null }, errors: [], request_id: "demo" }]; @@ -225,7 +262,7 @@ export function demoRoutes(): Route[] { ["GET", /^\/history\/([^/]+)\/restore-preview$/, (mm) => [200, restorePreview(decodeURIComponent(mm[1]))]], ["GET", /^\/certs$/, () => [200, certs()]], ["GET", /^\/settings$/, () => [200, { repo: { name: "home-routes", last_push_at: at(-2 * 3600) }, watch_seconds: 60 }]], - ...mockRoutes(newMock()), + ...mockRoutes(m), ]; } @@ -234,3 +271,21 @@ export function demoApi(): (method: string, path: string, body: Json) => { statu const routes = demoRoutes(); return (method, path, body) => respond(routes, method.toUpperCase(), path, body); } + +// What the demo may show (demo.test.ts, and the e2e suite on every page it visits). +const ALLOWED_TLDS = new Set(["test", "example", "invalid"]); +const DOC_NETS = ["192.0.2.", "198.51.100.", "203.0.113."]; +const FORBIDDEN = ["mark", "marek", "novak", "flowers", "esp32", "hyperv"]; + +/** What in a text could be real: addresses outside the documentation ranges, names outside .test. */ +export function realLooking(text: string): string[] { + const found: string[] = []; + for (const m of text.matchAll(/(? m[0].startsWith(n))) found.push(m[0]); + } + for (const m of text.matchAll(/(? new Date().toISOString(); -const later = (s: number) => new Date(Date.now() + s * 1000).toISOString(); +/** The stand-in's clock: the real one, or a fixed instant (the e2e suite's, so two takes of a screen match). */ +export const clock: { fixed: number | null } = { fixed: null }; +export const nowMs = () => clock.fixed ?? Date.now(); +const now = () => new Date(nowMs()).toISOString(); +const later = (s: number) => new Date(nowMs() + s * 1000).toISOString(); export function host(hostname: string, share: boolean) { return { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 409f695..760faa7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14,6 +14,9 @@ importers: specifier: workspace:* version: link:../../packages/ui devDependencies: + '@playwright/test': + specifier: 1.56.1 + version: 1.56.1 '@sveltejs/vite-plugin-svelte': specifier: ^5.0.3 version: 5.1.1(svelte@5.57.3)(vite@6.4.5) @@ -286,6 +289,11 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@playwright/test@1.56.1': + resolution: {integrity: sha512-vSMYtL/zOcFpvJCW71Q/OEGQb7KYBPAdKh35WNSkaZA75JlAO8ED8UN6GUNTm3drWomcbcqRPFqQbLae8yBTdg==} + engines: {node: '>=18'} + hasBin: true + '@rollup/rollup-android-arm-eabi@4.68.0': resolution: {integrity: sha512-Ta2n0ntLfzP0LqwwcXOIh2z0mnHjlxMS+h4Y9lo+w33Quyf9KFKEi9QZ2IKqeEBKr0qxNpXc/DQjz5KVIs8AEA==} cpu: [arm] @@ -642,6 +650,11 @@ packages: picomatch: optional: true + fsevents@2.3.2: + resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -736,6 +749,16 @@ packages: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} + playwright-core@1.56.1: + resolution: {integrity: sha512-hutraynyn31F+Bifme+Ps9Vq59hKuUCz7H1kDOcBs+2oGguKkWTU50bBWrtz34OUWmIwpBTWDxaRPXrIXkgvmQ==} + engines: {node: '>=18'} + hasBin: true + + playwright@1.56.1: + resolution: {integrity: sha512-aFi5B0WovBHTEvpM3DzXTUaeN6eN0qWnTkKx4NQaH4Wvcmc153PdaY2UBdSYKaGYw+UyWXSVyxDUg5DoPEttjw==} + engines: {node: '>=18'} + hasBin: true + postcss@8.5.32: resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} engines: {node: ^10 || ^12 || >=14} @@ -1119,6 +1142,10 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.6.0 + '@playwright/test@1.56.1': + dependencies: + playwright: 1.56.1 + '@rollup/rollup-android-arm-eabi@4.68.0': optional: true @@ -1419,6 +1446,9 @@ snapshots: optionalDependencies: picomatch: 4.0.7 + fsevents@2.3.2: + optional: true + fsevents@2.3.3: optional: true @@ -1515,6 +1545,14 @@ snapshots: picomatch@4.0.7: {} + playwright-core@1.56.1: {} + + playwright@1.56.1: + dependencies: + playwright-core: 1.56.1 + optionalDependencies: + fsevents: 2.3.2 + postcss@8.5.32: dependencies: nanoid: 3.3.20