114 lines
4.3 KiB
TypeScript
114 lines
4.3 KiB
TypeScript
// 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<string, string> = {
|
|
".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<Record<string, unknown>> {
|
|
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<string, unknown>) : {});
|
|
} catch {
|
|
ok({});
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
function serve(dist: string): Promise<Server> {
|
|
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<void>> {
|
|
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<void>((r) => server.close(() => r()));
|
|
remove();
|
|
};
|
|
}
|