@a2f0/agent-tool 0.1.72 → 0.1.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,82 @@
1
+ /** `agent-tool perf`: measures how fast a page becomes usable; PERF_USAGE lists the commands. */
2
+ import { writeFileSync, writeSync } from "node:fs";
3
+ import { measureLoad, shot } from "./browser";
4
+ import { compareImages } from "./diff";
5
+ import { moduleGraph } from "./graph";
6
+ import { type Options, PERF_USAGE, parseOptions } from "./options";
7
+ import { serve } from "./serve";
8
+
9
+ const print = (text: string) => {
10
+ writeSync(1, `${text}\n`);
11
+ };
12
+
13
+ async function measure(options: Options): Promise<void> {
14
+ const report = await measureLoad(options);
15
+ if (options.json) {
16
+ print(JSON.stringify(report, null, 2));
17
+ return;
18
+ }
19
+ const { url, readyMs } = report;
20
+ print(`${url} ready median ${readyMs.median} ms (min ${readyMs.min}, max ${readyMs.max}, ${readyMs.runs} runs)`);
21
+ print(
22
+ ` ${report.requests} requests, ${report.transferredBytes} bytes, network done at ${report.networkDoneMs} ms${report.pendingRequests ? ` (${report.pendingRequests} still pending)` : ""}; ${JSON.stringify(report.conditions)}`,
23
+ );
24
+ for (const row of report.waterfall ?? [])
25
+ print(` ${String(row.start).padStart(6)} ${String(row.end ?? "-").padStart(6)} ${String(row.bytes ?? "").padStart(8)} ${row.path}`);
26
+ if (report.cpu) {
27
+ printCpuRows("self", report.cpu.self);
28
+ printCpuRows("inclusive", report.cpu.inclusive);
29
+ }
30
+ }
31
+
32
+ function printCpuRows(title: string, rows: { fn: string; ms: number }[]): void {
33
+ print(` CPU ${title} (ms):`);
34
+ for (const row of rows) print(` ${row.ms.toFixed(1).padStart(8)} ${row.fn}`);
35
+ }
36
+
37
+ /**
38
+ * Runs one perf command. `serve` returns once it is listening and keeps the
39
+ * process alive; `diff` exits 1 when any pixel differs. Usage errors throw.
40
+ */
41
+ export async function perfCommand(argv: string[]): Promise<number> {
42
+ if (argv.includes("--help") || argv.includes("-h")) {
43
+ print(PERF_USAGE);
44
+ return 0;
45
+ }
46
+ const options = parseOptions(argv);
47
+ switch (options.command) {
48
+ case "serve": {
49
+ if (!options.args[0]) throw new Error("serve needs a directory.");
50
+ const server = serve(options.args[0], options.port, options.http1);
51
+ // Listening keeps the process alive; a port already in use ends it with 1.
52
+ return new Promise(resolve => {
53
+ server.once("listening", () => resolve(0));
54
+ server.once("error", () => resolve(1));
55
+ });
56
+ }
57
+ case "measure":
58
+ await measure(options);
59
+ return 0;
60
+ case "shot":
61
+ await shot(options);
62
+ return 0;
63
+ case "diff": {
64
+ const result = compareImages(options);
65
+ print(JSON.stringify(result));
66
+ return result.differing === 0 ? 0 : 1;
67
+ }
68
+ case "graph": {
69
+ const [root, ...entries] = options.args;
70
+ if (!root || entries.length === 0) throw new Error("graph needs a directory and at least one entry.");
71
+ const graph = moduleGraph(root, entries);
72
+ if (options.out) writeFileSync(options.out, `${JSON.stringify(graph, null, 2)}\n`);
73
+ print(JSON.stringify(graph));
74
+ return 0;
75
+ }
76
+ case "help":
77
+ print(PERF_USAGE);
78
+ return 0;
79
+ default:
80
+ throw new Error(`Unknown perf command '${options.command}'.\n\n${PERF_USAGE}`);
81
+ }
82
+ }
@@ -0,0 +1,115 @@
1
+ /** `perf diff`: pixel differences between two PNG screenshots, without a browser. */
2
+ import { readFileSync } from "node:fs";
3
+ import { inflateSync } from "node:zlib";
4
+ import type { Options } from "./options";
5
+
6
+ /** An 8-bit RGB or RGBA, non-interlaced PNG, as Chrome writes screenshots, decoded to RGBA. */
7
+ function decodePng(file: Buffer): { width: number; height: number; data: Uint8Array } {
8
+ const { width, height, channels, compressed } = readPngChunks(file);
9
+ const raw = inflateSync(compressed);
10
+ if (raw.length !== (width * channels + 1) * height) throw new Error("The PNG's image data is truncated or the wrong size.");
11
+ const pixels = unfilterRows(raw, width, height, channels);
12
+ return { width, height, data: toRgba(pixels, width * height, channels) };
13
+ }
14
+
15
+ /** The header fields and concatenated image data of a PNG, rejecting formats `decodePng` cannot read. */
16
+ function readPngChunks(file: Buffer): { width: number; height: number; channels: number; compressed: Buffer } {
17
+ if (file.subarray(0, 8).toString("hex") !== "89504e470d0a1a0a") throw new Error("Not a PNG.");
18
+ let header = { width: 0, height: 0, channels: 0 };
19
+ const chunks: Buffer[] = [];
20
+ for (let at = 8; at < file.length; ) {
21
+ const length = file.readUInt32BE(at),
22
+ type = file.toString("latin1", at + 4, at + 8),
23
+ body = file.subarray(at + 8, at + 8 + length);
24
+ if (type === "IHDR") header = pngHeader(body);
25
+ else if (type === "IDAT") chunks.push(body);
26
+ at += 12 + length;
27
+ }
28
+ return { ...header, compressed: Buffer.concat(chunks) };
29
+ }
30
+
31
+ /** The size and channel count an IHDR chunk gives, rejecting what `decodePng` cannot read. */
32
+ function pngHeader(body: Buffer): { width: number; height: number; channels: number } {
33
+ const width = body.readUInt32BE(0);
34
+ const height = body.readUInt32BE(4);
35
+ const [depth, colour, , , interlace] = [body[8], body[9], body[10], body[11], body[12]];
36
+ const channels = colour === 6 ? 4 : colour === 2 ? 3 : 0;
37
+ if (depth !== 8 || !channels || interlace !== 0) throw new Error("Only 8-bit RGB or RGBA, non-interlaced PNGs are supported.");
38
+ return { width, height, channels };
39
+ }
40
+
41
+ /** Reverses each scanline's filter, giving `channels` bytes per pixel. */
42
+ function unfilterRows(raw: Buffer, width: number, height: number, channels: number): Uint8Array {
43
+ const stride = width * channels;
44
+ const pixels = new Uint8Array(stride * height);
45
+ for (let y = 0; y < height; y += 1) unfilterRow(raw, pixels, y, stride, channels);
46
+ return pixels;
47
+ }
48
+
49
+ /** Reverses scanline `y`'s filter into `pixels`, reading the already decoded row above. */
50
+ function unfilterRow(raw: Buffer, pixels: Uint8Array, y: number, stride: number, channels: number): void {
51
+ const filter = raw[y * (stride + 1)]!,
52
+ row = y * stride;
53
+ if (filter > 4) throw new Error(`Unknown PNG row filter ${filter}.`);
54
+ for (let x = 0; x < stride; x += 1) {
55
+ const value = raw[y * (stride + 1) + 1 + x]!;
56
+ const left = x >= channels ? pixels[row + x - channels]! : 0,
57
+ up = y ? pixels[row - stride + x]! : 0;
58
+ const corner = x >= channels && y ? pixels[row - stride + x - channels]! : 0;
59
+ pixels[row + x] = (value + predictor(filter, left, up, corner)) & 255;
60
+ }
61
+ }
62
+
63
+ /** The byte a PNG filter type predicts from the left, upper and upper-left neighbours. */
64
+ function predictor(filter: number, left: number, up: number, corner: number): number {
65
+ if (filter === 1) return left;
66
+ if (filter === 2) return up;
67
+ if (filter === 3) return (left + up) >> 1;
68
+ if (filter !== 4) return 0;
69
+ const estimate = left + up - corner,
70
+ a = Math.abs(estimate - left),
71
+ b = Math.abs(estimate - up),
72
+ c = Math.abs(estimate - corner);
73
+ return a <= b && a <= c ? left : b <= c ? up : corner;
74
+ }
75
+
76
+ /** Widens RGB or RGBA pixels to RGBA, opaque where the image has no alpha. */
77
+ function toRgba(pixels: Uint8Array, count: number, channels: number): Uint8Array {
78
+ const data = new Uint8Array(count * 4);
79
+ for (let pixel = 0; pixel < count; pixel += 1) {
80
+ for (let c = 0; c < channels; c += 1) data[pixel * 4 + c] = pixels[pixel * channels + c]!;
81
+ if (channels === 3) data[pixel * 4 + 3] = 255;
82
+ }
83
+ return data;
84
+ }
85
+
86
+ /** Counts the pixels that differ between two PNG screenshots; `diff` prints the result. */
87
+ export function compareImages(options: Options) {
88
+ const [a, b] = options.args;
89
+ if (!a || !b) throw new Error("diff needs two PNG paths.");
90
+ const x = decodePng(readFileSync(a)),
91
+ y = decodePng(readFileSync(b));
92
+ if (x.width !== y.width || x.height !== y.height)
93
+ return { sizeMismatch: true, differing: -1, total: 0, maxChannelDelta: 255, cells: [] as { at: string; pixels: number }[] };
94
+ // Differences per 50-pixel cell, so a few moved stars read differently from a changed building.
95
+ const CELL = 50,
96
+ cells = new Map<string, number>();
97
+ let differing = 0,
98
+ maxChannelDelta = 0;
99
+ for (let i = 0; i < x.data.length; i += 4) {
100
+ let pixel = 0;
101
+ for (let c = 0; c < 4; c += 1) pixel = Math.max(pixel, Math.abs(x.data[i + c]! - y.data[i + c]!));
102
+ if (pixel > 0) {
103
+ differing += 1;
104
+ const index = i / 4,
105
+ key = `${Math.floor((index % x.width) / CELL) * CELL},${Math.floor(index / x.width / CELL) * CELL}`;
106
+ cells.set(key, (cells.get(key) ?? 0) + 1);
107
+ }
108
+ maxChannelDelta = Math.max(maxChannelDelta, pixel);
109
+ }
110
+ const busiest = [...cells]
111
+ .sort((first, second) => second[1] - first[1])
112
+ .slice(0, 20)
113
+ .map(([at, pixels]) => ({ at, pixels }));
114
+ return { sizeMismatch: false, differing, total: x.width * x.height, maxChannelDelta, cells: busiest };
115
+ }
@@ -0,0 +1,100 @@
1
+ /** `perf graph`: the relative import closure of ES modules, for preload lists generated from built files. */
2
+ import { readFileSync } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ /**
6
+ * The source with comments blanked and every string literal's contents replaced by a
7
+ * placeholder, keeping its quotes, so a scan for imports sees neither commented-out imports nor
8
+ * text that only looks like one. Specifiers are kept in `strings`, indexed by placeholder.
9
+ * Regular expression literals are not recognised: a quote inside one can hide later imports.
10
+ */
11
+ function tokens(source: string): { code: string; strings: string[] } {
12
+ let code = "",
13
+ i = 0;
14
+ const strings: string[] = [];
15
+ while (i < source.length) {
16
+ const char = source[i]!;
17
+ const skipped = comment(source, i);
18
+ if (skipped) {
19
+ code += skipped.text;
20
+ i = skipped.end;
21
+ continue;
22
+ }
23
+ if (char === "'" || char === '"' || char === "`") {
24
+ const literal = stringLiteral(source, i);
25
+ code += `${char}${strings.length}${char}`;
26
+ strings.push(literal.text);
27
+ i = literal.end;
28
+ continue;
29
+ }
30
+ code += char;
31
+ i += 1;
32
+ }
33
+ return { code, strings };
34
+ }
35
+
36
+ /** The comment starting at `start`, if one does: the index just past it (a line comment's newline stays) and what replaces it in the code. */
37
+ function comment(source: string, start: number): { end: number; text: string } | undefined {
38
+ if (source[start] !== "/") return undefined;
39
+ if (source[start + 1] === "/") {
40
+ const end = source.indexOf("\n", start);
41
+ return { end: end < 0 ? source.length : end, text: "" };
42
+ }
43
+ if (source[start + 1] !== "*") return undefined;
44
+ const end = source.indexOf("*/", start + 2);
45
+ return { end: end < 0 ? source.length : end + 2, text: " " };
46
+ }
47
+
48
+ /** The contents of the string literal whose quote is at `start`, escapes kept, and the index just past its closing quote. */
49
+ function stringLiteral(source: string, start: number): { text: string; end: number } {
50
+ const quote = source[start];
51
+ let j = start + 1,
52
+ text = "";
53
+ while (j < source.length && source[j] !== quote) {
54
+ if (source[j] === "\\") {
55
+ text += source[j]! + (source[j + 1] ?? "");
56
+ j += 2;
57
+ continue;
58
+ }
59
+ text += source[j]!;
60
+ j += 1;
61
+ }
62
+ return { text, end: j + 1 };
63
+ }
64
+
65
+ /** Relative imports of an ES module's source: static `import`/`export from`, bare `import "x"`, and literal `import("x")`. */
66
+ export function importsOf(source: string): string[] {
67
+ const { code, strings } = tokens(source);
68
+ const found = new Set<string>();
69
+ const patterns = [
70
+ /(?:^|[^\w$.])(?:import|export)\b[^;'"`]*?\bfrom\s*["'](\d+)["']/g,
71
+ /(?:^|[^\w$.])import\s*["'](\d+)["']/g,
72
+ /(?:^|[^\w$.])import\s*\(\s*["'](\d+)["']\s*\)/g,
73
+ ];
74
+ for (const pattern of patterns)
75
+ for (const match of code.matchAll(pattern)) {
76
+ const specifier = strings[Number(match[1])]!;
77
+ if (specifier.startsWith(".")) found.add(specifier);
78
+ }
79
+ return [...found];
80
+ }
81
+
82
+ /** Every module reachable from the entries through relative imports, as paths within `root`, entries first. */
83
+ export function moduleGraph(root: string, entries: string[]): string[] {
84
+ const seen = new Set<string>();
85
+ const walk = (rel: string, from: string | undefined) => {
86
+ const where = from === undefined ? `entry ${rel}` : `${rel}, imported by ${from}`;
87
+ if (rel === ".." || rel.startsWith("../") || path.posix.isAbsolute(rel)) throw new Error(`The graph leaves ${root} at ${where}.`);
88
+ if (seen.has(rel)) return;
89
+ seen.add(rel);
90
+ let source: string;
91
+ try {
92
+ source = readFileSync(path.join(root, rel), "utf8");
93
+ } catch (error) {
94
+ throw new Error(`Cannot read ${where}: ${(error as NodeJS.ErrnoException).code ?? (error as Error).message}.`);
95
+ }
96
+ for (const spec of importsOf(source)) walk(path.posix.normalize(path.posix.join(path.posix.dirname(rel), spec)), rel);
97
+ };
98
+ for (const entry of entries) walk(path.posix.normalize(entry), undefined);
99
+ return [...seen];
100
+ }
@@ -0,0 +1,107 @@
1
+ /** `agent-tool perf` arguments: a command, its positional arguments, and its measuring conditions. */
2
+
3
+ export const PERF_USAGE = `Usage: agent-tool perf <command> [args...] [options]
4
+
5
+ Measures how fast a page becomes usable, so a performance pass compares
6
+ rounds by numbers rather than impressions. Chrome is driven through the
7
+ measured repository's own \`playwright\` dependency, found from the working
8
+ directory or --from <repository>.
9
+
10
+ serve <dir> [--port 8765] [--http1] serve a production build, compressed, revalidating
11
+ measure <url> --ready <js> [...] cold loads: median time to ready, requests, bytes
12
+ --waterfall, --profile, --json
13
+ shot <url> --ready <js> --out <png> a seeded screenshot of the ready state; --eval <js>, --hide <css>
14
+ diff <a.png> <b.png> count differing pixels between two screenshots; exit 1 on any
15
+ graph <dir> <entry...> [--out file] an ES module's relative static and dynamic imports
16
+
17
+ Conditions: --runs 5, --latency 40 (ms), --mbps 20, --cpu 1 (slowdown),
18
+ --width 1600, --height 900; --no-seed leaves Math.random unseeded.`;
19
+
20
+ export interface Options {
21
+ command: string;
22
+ args: string[];
23
+ ready: string;
24
+ runs: number;
25
+ latency: number;
26
+ mbps: number;
27
+ cpu: number;
28
+ width: number;
29
+ height: number;
30
+ port: number;
31
+ out: string | undefined;
32
+ hide: string | undefined;
33
+ eval: string | undefined;
34
+ from: string | undefined;
35
+ waterfall: boolean;
36
+ profile: boolean;
37
+ json: boolean;
38
+ seed: boolean;
39
+ http1: boolean;
40
+ }
41
+
42
+ type NumberOption = "runs" | "latency" | "mbps" | "cpu" | "width" | "height" | "port";
43
+ type StringOption = "ready" | "out" | "hide" | "eval" | "from";
44
+ type FlagOption = "waterfall" | "profile" | "json" | "seed" | "http1";
45
+ const NUMBERS = new Set<string>(["runs", "latency", "mbps", "cpu", "width", "height", "port"] satisfies NumberOption[]);
46
+ const STRINGS = new Set<string>(["ready", "out", "hide", "eval", "from"] satisfies StringOption[]);
47
+ const FLAGS = new Set<string>(["waterfall", "profile", "json", "seed", "http1"] satisfies FlagOption[]);
48
+ const isNumber = (name: string): name is NumberOption => NUMBERS.has(name);
49
+ const isString = (name: string): name is StringOption => STRINGS.has(name);
50
+ const isFlag = (name: string): name is FlagOption => FLAGS.has(name);
51
+
52
+ export function parseOptions(argv: string[]): Options {
53
+ const options: Options = {
54
+ command: argv[0] ?? "help",
55
+ args: [],
56
+ ready: "document.readyState === 'complete'",
57
+ runs: 5,
58
+ latency: 40,
59
+ mbps: 20,
60
+ cpu: 1,
61
+ width: 1600,
62
+ height: 900,
63
+ port: 8765,
64
+ out: undefined,
65
+ hide: undefined,
66
+ eval: undefined,
67
+ from: undefined,
68
+ waterfall: false,
69
+ profile: false,
70
+ json: false,
71
+ seed: true,
72
+ http1: false,
73
+ };
74
+ for (let i = 1; i < argv.length; i += 1) i = readArgument(options, argv, i);
75
+ if (options.runs < 1) throw new Error("--runs needs at least 1.");
76
+ for (const name of ["runs", "width", "height", "port"] as const) if (!Number.isInteger(options[name])) throw new Error(`--${name} needs a whole number.`);
77
+ if (options.width < 1 || options.height < 1) throw new Error("--width and --height need at least 1.");
78
+ if (options.port > 65535) throw new Error("--port needs a port number, at most 65535.");
79
+ return options;
80
+ }
81
+
82
+ /** Applies the argument at `index` to `options`, returning the index of the last argument it used. */
83
+ function readArgument(options: Options, argv: string[], index: number): number {
84
+ const arg = argv[index]!;
85
+ if (!arg.startsWith("--")) {
86
+ options.args.push(arg);
87
+ return index;
88
+ }
89
+ const name = arg.slice(2);
90
+ if (name === "no-seed") options.seed = false;
91
+ else if (isFlag(name)) options[name] = true;
92
+ else if (isNumber(name) || isString(name)) {
93
+ setValue(options, name, arg, argv[index + 1]);
94
+ return index + 1;
95
+ } else throw new Error(`Unknown option ${arg}.`);
96
+ return index;
97
+ }
98
+
99
+ /** Stores the value that follows a `--name` option, as a number where the option takes one. */
100
+ function setValue(options: Options, name: NumberOption | StringOption, arg: string, value: string | undefined): void {
101
+ if (value === undefined) throw new Error(`${arg} needs a value.`);
102
+ if (isNumber(name)) {
103
+ const number = Number(value);
104
+ if (!Number.isFinite(number) || number < 0) throw new Error(`${arg} needs a non-negative number.`);
105
+ options[name] = number;
106
+ } else options[name] = value;
107
+ }
@@ -0,0 +1,163 @@
1
+ /**
2
+ * `perf serve`: a production build served the way a CDN with revalidation serves
3
+ * it, so local measurements stand in for the deployment.
4
+ */
5
+ import { spawnSync } from "node:child_process";
6
+ import { mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, type Stats, statSync } from "node:fs";
7
+ import { createServer, type IncomingMessage, ServerResponse } from "node:http";
8
+ import { createSecureServer, type Http2ServerRequest, type Http2ServerResponse } from "node:http2";
9
+ import type { AddressInfo } from "node:net";
10
+ import { tmpdir } from "node:os";
11
+ import path from "node:path";
12
+ import { gzipSync } from "node:zlib";
13
+
14
+ const TYPES: Record<string, string> = {
15
+ ".html": "text/html",
16
+ ".js": "text/javascript",
17
+ ".mjs": "text/javascript",
18
+ ".css": "text/css",
19
+ ".json": "application/json",
20
+ ".svg": "image/svg+xml",
21
+ ".png": "image/png",
22
+ ".jpg": "image/jpeg",
23
+ ".ico": "image/x-icon",
24
+ ".wasm": "application/wasm",
25
+ ".txt": "text/plain",
26
+ };
27
+ const COMPRESSED = new Set([".html", ".js", ".mjs", ".css", ".json", ".svg", ".txt"]);
28
+
29
+ /** A file version's validator: its size and modification time. */
30
+ const etagOf = (stats: Stats) => `"${stats.size}-${stats.mtimeMs}"`;
31
+
32
+ /** A throwaway self-signed certificate for localhost, so the server can speak HTTP/2 as CDNs do. */
33
+ function certificate(): { key: Buffer; cert: Buffer } {
34
+ const directory = mkdtempSync(path.join(tmpdir(), "perf-cert-"));
35
+ try {
36
+ const result = spawnSync(
37
+ "openssl",
38
+ [
39
+ "req",
40
+ "-x509",
41
+ "-newkey",
42
+ "rsa:2048",
43
+ "-nodes",
44
+ "-days",
45
+ "2",
46
+ "-subj",
47
+ "/CN=localhost",
48
+ "-keyout",
49
+ path.join(directory, "key.pem"),
50
+ "-out",
51
+ path.join(directory, "cert.pem"),
52
+ ],
53
+ { stdio: "ignore" },
54
+ );
55
+ if (result.status !== 0) throw new Error("openssl could not make a localhost certificate; pass --http1 to serve without TLS.");
56
+ return { key: readFileSync(path.join(directory, "key.pem")), cert: readFileSync(path.join(directory, "cert.pem")) };
57
+ } finally {
58
+ rmSync(directory, { recursive: true, force: true });
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Serves a build the way a CDN with revalidation does: over HTTP/2 (browsers allow six
64
+ * HTTP/1.1 connections per host, which queues module graphs that a CDN serves in parallel),
65
+ * text compressed once per file version so compression never costs request time, and
66
+ * `no-cache` with an ETag. Paths outside `root` 404.
67
+ */
68
+ export function serve(root: string, port: number, http1 = false) {
69
+ const base = realpathSync(path.resolve(root));
70
+ const cache = new Map<string, { key: string; body: Buffer }>();
71
+ // The file a path names, resolved through symlinks, or undefined when that leaves the root.
72
+ const inside = (pathname: string) => {
73
+ try {
74
+ const file = realpathSync(path.resolve(base, `.${pathname}`));
75
+ return file.startsWith(base + path.sep) && statSync(file).isFile() ? file : undefined;
76
+ } catch {
77
+ return undefined;
78
+ }
79
+ };
80
+ const compressed = (file: string, etag: string, body: Buffer) => {
81
+ if (cache.get(file)?.key !== etag) cache.set(file, { key: etag, body: gzipSync(body, { level: 9 }) });
82
+ return cache.get(file)!.body;
83
+ };
84
+ // Compress every text file before serving, so the first measured load pays no compression.
85
+ // Symlinked directories are left to be compressed on request.
86
+ const warm = (directory: string) => {
87
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
88
+ const full = path.join(directory, entry.name);
89
+ if (entry.isDirectory()) {
90
+ warm(full);
91
+ continue;
92
+ }
93
+ const file = inside(`/${path.relative(base, full).split(path.sep).join("/")}`);
94
+ if (!file || !COMPRESSED.has(path.extname(file).toLowerCase())) continue;
95
+ compressed(file, etagOf(statSync(file)), readFileSync(file));
96
+ }
97
+ };
98
+ warm(base);
99
+ const handler = (request: IncomingMessage | Http2ServerRequest, response: ServerResponse | Http2ServerResponse) => {
100
+ // Another site's page reaching this port through a name it rebound to 127.0.0.1 names that host.
101
+ if (!loopbackHost(request)) return respond(response, { status: 421 });
102
+ try {
103
+ const pathname = requestPath(request.url);
104
+ const file = pathname ? inside(pathname) : undefined;
105
+ respond(response, file ? reply(request, file, compressed) : { status: 404 });
106
+ } catch {
107
+ // A file removed or replaced mid-request, as a rebuild does, fails that request, not the server.
108
+ if (!response.headersSent) respond(response, { status: 404 });
109
+ }
110
+ };
111
+ const server = http1 ? createServer(handler) : createSecureServer({ ...certificate(), allowHTTP1: true }, handler);
112
+ server.once("error", error => {
113
+ process.stderr.write(`perf serve: ${error.message}\n`);
114
+ process.exitCode = 1;
115
+ });
116
+ // Loopback only: the build is for this machine's browser, not the network.
117
+ return server.listen(port, "127.0.0.1", () =>
118
+ console.log(`Serving ${base} at ${http1 ? "http" : "https"}://127.0.0.1:${(server.address() as AddressInfo).port}/`),
119
+ );
120
+ }
121
+
122
+ interface Reply {
123
+ status: number;
124
+ headers?: Record<string, string>;
125
+ body?: Buffer;
126
+ }
127
+
128
+ /** What a request for a served file gets: 304 when its ETag matches, else the file, gzipped when its type and the client allow. */
129
+ function reply(request: IncomingMessage | Http2ServerRequest, file: string, compressed: (file: string, etag: string, body: Buffer) => Buffer): Reply {
130
+ const extension = path.extname(file).toLowerCase();
131
+ const etag = etagOf(statSync(file));
132
+ const headers: Record<string, string> = { "content-type": TYPES[extension] ?? "application/octet-stream", "cache-control": "no-cache", etag };
133
+ if (request.headers["if-none-match"] === etag) return { status: 304, headers };
134
+ let body: Buffer = readFileSync(file);
135
+ if (COMPRESSED.has(extension) && /\bgzip\b/.test(String(request.headers["accept-encoding"] ?? ""))) {
136
+ body = compressed(file, etag, body);
137
+ headers["content-encoding"] = "gzip";
138
+ }
139
+ return { status: 200, headers, body };
140
+ }
141
+
142
+ function respond(response: ServerResponse | Http2ServerResponse, { status, headers, body }: Reply): void {
143
+ if (response instanceof ServerResponse) response.writeHead(status, headers).end(body);
144
+ else if (body) response.writeHead(status, headers).end(body);
145
+ else response.writeHead(status, headers).end();
146
+ }
147
+
148
+ /** Whether a request names this machine (`127.0.0.1` or `localhost`, any port) as its host. */
149
+ function loopbackHost(request: IncomingMessage | Http2ServerRequest): boolean {
150
+ const host = String(request.headers[":authority"] ?? request.headers.host ?? "").toLowerCase();
151
+ return /^(?:127\.0\.0\.1|localhost)(?::\d+)?$/.test(host);
152
+ }
153
+
154
+ /** The decoded path a request names, a directory's naming its index.html; empty when it does not decode. */
155
+ function requestPath(url: string | undefined): string {
156
+ let pathname: string;
157
+ try {
158
+ pathname = decodeURIComponent(new URL(url ?? "/", "http://localhost").pathname);
159
+ } catch {
160
+ pathname = "";
161
+ }
162
+ return pathname.endsWith("/") ? `${pathname}index.html` : pathname;
163
+ }
@@ -19,7 +19,7 @@ export type Decision = "allow" | "ask";
19
19
  export interface CatalogEntry { command: string; class: PermissionClass; applyClass?: PermissionClass }
20
20
 
21
21
  export const CATALOG: CatalogEntry[] = [
22
- ...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "hooks check", "push-gate hook", "push-gate check", "repo base-health", "review carry", "images list", "graph check", "state-machines", "permissions show", "permissions check", "proc list"]
22
+ ...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "hooks check", "push-gate hook", "push-gate check", "repo base-health", "review carry", "images list", "graph check", "state-machines", "permissions show", "permissions check", "proc list", "perf diff"]
23
23
  .map(command => ({ command, class: "read" as const })),
24
24
  ...["bun install", "bun update", "bun remove", "bun test", "branch create", "versions bump", "versions prepare", "versions resolve-conflicts", "images build", "screenshots build", "review", "init", "proc stop"]
25
25
  .map(command => ({ command, class: "local" as const })),
@@ -40,6 +40,9 @@ export const CATALOG: CatalogEntry[] = [
40
40
  ];
41
41
  // `run`, `run-group`, `push-gate run` and `proc start` execute arbitrary commands, so they stay unclassified and keep the harness default.
42
42
  // `seo probe` requests whatever host its arguments name, and public hosts its fetched pages name, like curl, so it keeps the harness default too.
43
+ // So do `perf measure` and `perf shot`, which open any URL in Chrome and evaluate the JavaScript their arguments give,
44
+ // `perf serve`, which serves a directory to every local user, `perf graph`, whose --out overwrites any file, and `space`, whose --apply removes output in other
45
+ // checkouts and developer caches across the machine, with --include-busy even where other sessions work.
43
46
  // `bun x` runs only executables that `permissions.executables` classifies; project.ts adds those.
44
47
  // Package scripts are not classified, so `bun run` keeps the harness default.
45
48