/**
* What every page must hold to, checked on each build and by the tests.
*
* - Nothing loads from another host: every picture, font and stylesheet is
* the site's own (a path starting with "/"). No script, frame or form.
* - A link goes only to the site's own pages, /delete, the support address,
* the few outside pages a reader is sent to (pages.ts OUTSIDE), or a store.
* - Every file a page names is in static/.
* - Each page, with everything it loads apart from screenshots and photos
* (static/shots, static/photos; fonts and all, as a first visit loads them), is under 200 KB as it travels: text
* compressed, as Cloudflare sends it; pictures and fonts as they are.
* - Every screenshot is there, not blank or one flat colour, and its pen
* mark sits on something drawn (checkShots, below).
*/
import { createHash } from "node:crypto";
import { gzipSync } from "node:zlib";
import { existsSync, readFileSync, statSync } from "node:fs";
import path from "node:path";
import { OUTSIDE, OWN_PATHS, STORE, TEST } from "../pages/pages.ts";
import { blanksIn } from "../pages/blanks.ts";
export const BUDGET = 200 * 1024;
/** Every URL a page loads (not links): src, srcset, link href, CSS url(). */
export function loads(page: string): string[] {
const out: string[] = [];
for (const m of page.matchAll(/\bsrc="([^"]+)"/g)) out.push(m[1]!);
for (const m of page.matchAll(/\bsrcset="([^"]+)"/g)) out.push(...m[1]!.split(",").map((s) => s.trim().split(/\s+/)[0]!));
for (const m of page.matchAll(/]*\brel="(?:icon|stylesheet|preload)"[^>]*\bhref="([^"]+)"/g)) out.push(m[1]!);
for (const m of page.matchAll(/url\(([^)]+)\)/g)) out.push(m[1]!.replace(/["']/g, ""));
return out;
}
export const links = (page: string): string[] => [...page.matchAll(/]*\bhref="([^"]*)"/gi)].map((m) => m[1]!);
export function linkAllowed(href: string): boolean {
if (href.startsWith("#")) return true;
const [p, anchor] = href.split("#");
if (anchor !== undefined && /^\/[a-z0-9-]*$/.test(p!)) return (OWN_PATHS as readonly string[]).includes(p!);
return (
(OWN_PATHS as readonly string[]).includes(href) ||
(OUTSIDE as readonly string[]).includes(href) ||
STORE.test(href) ||
TEST.test(href) ||
blanksIn(href).length === 1
);
}
/**
* The files the build writes itself rather than copies from static/ (the stylesheet), by their path on the site.
* A page's weight counts what they load in turn (the fonts cotton.css names), once each, as a first visit loads them.
*/
export type Generated = Record;
export function checkSite(pages: Record, staticDir: string, generated: Generated = {}): string[] {
const problems: string[] = [];
// What travels: text (pages, the stylesheet, an SVG) as Cloudflare sends it, compressed (gzip here, a little more
// than the brotli it prefers); pictures and fonts, already compressed, as they are.
const sent = (text: string | Buffer) => gzipSync(text, { level: 9 }).length;
const size = (url: string): number | null => {
if (url in generated) return sent(generated[url]!);
const file = path.join(staticDir, url);
if (!existsSync(file)) return null;
return /\.(css|svg|html|txt)$/.test(url) ? sent(readFileSync(file)) : statSync(file).size;
};
for (const [name, page] of Object.entries(pages)) {
if (/<(script|iframe|form|object|embed)\b/i.test(page)) problems.push(`${name} has a script, frame or form`);
let bytes = sent(page);
const all = new Set(loads(page));
for (const url of [...all]) if (url in generated) for (const inner of loads(generated[url]!)) all.add(inner);
for (const url of all) {
if (url.startsWith("data:")) continue; // drawn inline (the stylesheet's tick): no request at all
if (!url.startsWith("/") || url.startsWith("//")) {
problems.push(`${name} loads ${url} from another host`);
continue;
}
const n = size(url);
if (n === null) {
problems.push(`${name} loads ${url}, which is not in static/`);
continue;
}
if (!url.startsWith("/shots/") && !url.startsWith("/photos/") && !url.includes("@2x")) bytes += n;
}
for (const href of links(page)) if (!linkAllowed(href)) problems.push(`${name} links to ${href}`);
for (const m of page.matchAll(/]*\bcontent="(https?:[^"]+)"/g)) {
if (!m[1]!.startsWith("https://cottondb.com/")) problems.push(`${name} names ${m[1]} in its head`);
else if (/\.(png|webp|jpg)$/.test(m[1]!) && !existsSync(path.join(staticDir, m[1]!.slice("https://cottondb.com".length))))
problems.push(`${name}'s link preview ${m[1]} is not in static/`);
}
for (const m of page.matchAll(/]*\brel="canonical"[^>]*\bhref="([^"]+)"/g))
if (!m[1]!.startsWith("https://cottondb.com/")) problems.push(`${name}'s canonical link ${m[1]} is not on cottondb.com`);
if (bytes > BUDGET) problems.push(`${name} weighs ${Math.round(bytes / 1024)} KB without screenshots (the limit is ${BUDGET / 1024} KB)`);
}
return problems;
}
/** The least a screen must hold: a blank or one-colour picture (a failed capture) falls under these. */
export const SCREEN = { spread: 12, flat: 0.95 };
/** The least the patch under a pen mark must hold: a mark on empty ground falls under these. */
export const MARKED = { spread: 8, flat: 0.92 };
interface Measured {
sha256: string;
spread: number;
flat: number;
mark?: unknown;
markSpread?: number;
markFlat?: number;
}
/**
* Every screenshot apps.json names: there, not blank, not nearly one flat colour, and its pen mark on drawn
* content inside the picture. The measures come from tools/site_pictures.py, which writes them beside the
* pictures (static/shots//manifest.json); a manifest that does not match the file served, or a mark moved
* since it was measured, fails too, so the numbers are always the served picture's own. Whether the mark
* names the right thing is for a person to look at: this proves it is on something, in the picture.
*/
export function checkShots(
apps: readonly { id: string; shots: readonly { file: string; mark?: { ring?: number[]; arrow?: number[] } }[] }[],
staticDir: string,
): string[] {
const problems: string[] = [];
for (const app of apps) {
const dir = path.join(staticDir, "shots", app.id);
const manifestFile = path.join(dir, "manifest.json");
if (!existsSync(manifestFile)) {
problems.push(`${app.id}: no static/shots/${app.id}/manifest.json (run: pnpm pictures ${app.id})`);
continue;
}
const manifest = JSON.parse(readFileSync(manifestFile, "utf8")) as Record;
for (const s of app.shots) {
const where = `${app.id}/${s.file}`;
const file = path.join(dir, `${s.file}.webp`);
if (!existsSync(file) || !existsSync(path.join(dir, `${s.file}@2x.webp`))) {
problems.push(`${where}: the screenshot is missing (run: pnpm pictures ${app.id})`);
continue;
}
const m = manifest[s.file];
if (!m) {
problems.push(`${where}: not measured (run: pnpm pictures --measure)`);
continue;
}
if (createHash("sha256").update(readFileSync(file)).digest("hex") !== m.sha256)
problems.push(`${where}: the picture changed since it was measured (run: pnpm pictures --measure)`);
if (m.spread < SCREEN.spread || m.flat > SCREEN.flat)
problems.push(`${where}: the screenshot is blank or nearly one flat colour (spread ${m.spread}, ${Math.round(m.flat * 100)}% one grey)`);
if (s.mark) {
const v = s.mark.ring ?? s.mark.arrow ?? [];
if (v.length !== 4 || v.some((n) => n < 0 || n > 100)) problems.push(`${where}: its pen mark is not four numbers inside the picture (0 to 100)`);
if (JSON.stringify(m.mark) !== JSON.stringify(s.mark)) problems.push(`${where}: its pen mark moved since it was measured (run: pnpm pictures --measure)`);
else if ((m.markSpread ?? 0) < MARKED.spread || (m.markFlat ?? 1) > MARKED.flat)
problems.push(`${where}: its pen mark lies on empty ground, not on anything in the screen (spread ${m.markSpread})`);
}
}
}
return problems;
}