trivium 0.0.0 → 0.1.0

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.
package/src/page.ts ADDED
@@ -0,0 +1,263 @@
1
+ import { nowMs } from "./env.ts";
2
+ import { TriviumError } from "./errors.ts";
3
+
4
+ /** A browser trivium drives through `Bun.WebView`. */
5
+ export type Browser = "chrome" | "webkit";
6
+
7
+ // spec: Lighthouse's presets as it applies them with
8
+ // --throttling-method=devtools, so the numbers match that run's: its
9
+ // simulated round trip times 3.75 as per-request latency, its
10
+ // throughput times 0.9, in kbit/s of 1,024 bits. Lighthouse applies no
11
+ // network throttling on desktop, which would make it `none`, so desktop
12
+ // is its Dense 4G (40 ms, 10,240 kbit/s) through the same factors.
13
+ const RTT_FACTOR = 3.75;
14
+ const THROUGHPUT_FACTOR = 0.9;
15
+ export type Throttle = "mobile" | "desktop" | "none";
16
+
17
+ interface Preset {
18
+ latencyMs: number;
19
+ downKbps: number;
20
+ upKbps: number;
21
+ cpuSlowdown: number;
22
+ }
23
+
24
+ const THROTTLE: Record<Throttle, Preset | undefined> = {
25
+ mobile: {
26
+ latencyMs: 150 * RTT_FACTOR,
27
+ downKbps: 1.6 * 1024 * THROUGHPUT_FACTOR,
28
+ upKbps: 750 * THROUGHPUT_FACTOR,
29
+ cpuSlowdown: 4,
30
+ },
31
+ desktop: {
32
+ latencyMs: 40 * RTT_FACTOR,
33
+ downKbps: 10 * 1024 * THROUGHPUT_FACTOR,
34
+ upKbps: 10 * 1024 * THROUGHPUT_FACTOR,
35
+ cpuSlowdown: 1,
36
+ },
37
+ none: undefined,
38
+ };
39
+
40
+ // CDP takes bytes per second, so kbit/s convert as Lighthouse converts
41
+ // them, rounding down.
42
+ const toBytesPerSecond = (kbps: number) => Math.floor((kbps * 1024) / 8);
43
+
44
+ export const THROTTLES: readonly Throttle[] = ["mobile", "desktop", "none"];
45
+
46
+ interface PageOptions {
47
+ browser: Browser;
48
+ throttle: Throttle;
49
+ // Runs before the page's own scripts on Chrome; on WebKit, which can't
50
+ // inject one, right after each navigation, so its observers read
51
+ // buffered entries.
52
+ initScript?: string;
53
+ // Keep the HTTP cache on, to measure a repeat visit.
54
+ cache?: boolean;
55
+ }
56
+
57
+ interface Page {
58
+ readonly view: Bun.WebView;
59
+ readonly browser: Browser;
60
+ navigate(url: string): Promise<void>;
61
+ settle(options?: { quietMs?: number; timeoutMs?: number }): Promise<void>;
62
+ close(): void;
63
+ }
64
+
65
+ const VIEWPORT = { width: 1400, height: 900 };
66
+
67
+ // The page-side poll `waitFor` runs: one round trip, resolving within a
68
+ // frame of the condition instead of at the next poll from Bun.
69
+ const poll = (
70
+ expression: string,
71
+ timeoutMs: number,
72
+ ) => `new Promise((resolve) => {
73
+ const end = performance.now() + ${timeoutMs};
74
+ (function check() {
75
+ let value;
76
+ try { value = (${expression}); } catch {}
77
+ if (value) resolve(true);
78
+ else if (performance.now() > end) resolve(false);
79
+ else setTimeout(check, 16);
80
+ })();
81
+ })`;
82
+
83
+ // `what` names the state in the error, in a person's words, since the
84
+ // page-side expression means nothing to someone who didn't write it.
85
+ export async function waitFor(
86
+ view: Bun.WebView,
87
+ expression: string,
88
+ what: string,
89
+ timeoutMs = 30_000,
90
+ ): Promise<void> {
91
+ const met = await view.evaluate<boolean>(poll(expression, timeoutMs));
92
+ if (!met) {
93
+ throw new TriviumError(
94
+ "TV_TIMEOUT",
95
+ `trivium: the page didn't reach ${what} within ${timeoutMs / 1000} s: check the URL, and readyMark in the config`,
96
+ );
97
+ }
98
+ }
99
+
100
+ const IDLE = `new Promise((resolve) => (window.requestIdleCallback ?? setTimeout)(() => resolve(), { timeout: 1000 }))`;
101
+
102
+ // WebKit has no CDP to report requests in flight, so it settles on what
103
+ // the page reports: no new resource entry for `quiet` ms, then an idle
104
+ // callback, and again if one arrived during it.
105
+ const settleInPage = (
106
+ quietMs: number,
107
+ timeoutMs: number,
108
+ ) => `new Promise((resolve) => {
109
+ const end = performance.now() + ${timeoutMs};
110
+ const count = () => performance.getEntriesByType("resource").length;
111
+ let seen = count(), since = performance.now();
112
+ (function check() {
113
+ if (count() !== seen) { seen = count(); since = performance.now(); }
114
+ if (performance.now() > end) return resolve(false);
115
+ if (performance.now() - since < ${quietMs}) return setTimeout(check, 25);
116
+ const before = seen;
117
+ (window.requestIdleCallback ?? setTimeout)(() => {
118
+ if (count() === before) resolve(true);
119
+ else { seen = count(); since = performance.now(); setTimeout(check, 25); }
120
+ }, { timeout: 1000 });
121
+ })();
122
+ })`;
123
+
124
+ async function nextFrame(view: Bun.WebView): Promise<void> {
125
+ await view.evaluate(
126
+ "new Promise((resolve) => requestAnimationFrame(() => setTimeout(resolve, 0)))",
127
+ );
128
+ }
129
+
130
+ function openFailed(browser: Browser, error: unknown): TriviumError {
131
+ const message = error instanceof Error ? error.message : String(error);
132
+ const fix =
133
+ browser === "chrome"
134
+ ? "install Chrome, or set BUN_CHROME_PATH to its binary"
135
+ : "WebKit runs on macOS only: pass --browser chrome";
136
+ return new TriviumError(
137
+ "TV_UNSUPPORTED",
138
+ `trivium: ${browser} didn't start: ${message}: ${fix}`,
139
+ { cause: error },
140
+ );
141
+ }
142
+
143
+ async function openChrome(options: PageOptions): Promise<Page> {
144
+ let view: Bun.WebView;
145
+ try {
146
+ // `url: false`: never attach to the person's own Chrome.
147
+ view = new Bun.WebView({
148
+ ...VIEWPORT,
149
+ backend: { type: "chrome", url: false },
150
+ });
151
+ // cdp() has no session until a first navigation.
152
+ await view.navigate("about:blank");
153
+ } catch (error) {
154
+ throw openFailed("chrome", error);
155
+ }
156
+ const pending = new Set<string>();
157
+ let changedMs = nowMs();
158
+ const track = (requestId: string, inFlight: boolean) => {
159
+ if (inFlight) pending.add(requestId);
160
+ else pending.delete(requestId);
161
+ changedMs = nowMs();
162
+ };
163
+ view.addEventListener<{ requestId: string }>(
164
+ "Network.requestWillBeSent",
165
+ (event) => track(event.data.requestId, true),
166
+ );
167
+ for (const done of [
168
+ "Network.loadingFinished",
169
+ "Network.loadingFailed",
170
+ ] as const) {
171
+ view.addEventListener<{ requestId: string }>(done, (event) =>
172
+ track(event.data.requestId, false),
173
+ );
174
+ }
175
+ await view.cdp("Network.enable");
176
+ // Chrome is one process for every view, and so is its HTTP cache: a
177
+ // cold load turns it off rather than trusting a fresh view.
178
+ await view.cdp("Network.setCacheDisabled", {
179
+ cacheDisabled: options.cache !== true,
180
+ });
181
+ const preset = THROTTLE[options.throttle];
182
+ if (preset) {
183
+ await view.cdp("Network.emulateNetworkConditions", {
184
+ offline: false,
185
+ latency: preset.latencyMs,
186
+ downloadThroughput: toBytesPerSecond(preset.downKbps),
187
+ uploadThroughput: toBytesPerSecond(preset.upKbps),
188
+ });
189
+ await view.cdp("Emulation.setCPUThrottlingRate", {
190
+ rate: preset.cpuSlowdown,
191
+ });
192
+ }
193
+ if (options.initScript !== undefined) {
194
+ await view.cdp("Page.addScriptToEvaluateOnNewDocument", {
195
+ source: options.initScript,
196
+ });
197
+ }
198
+ // No request in flight for `quietMs`, then an idle callback, and again
199
+ // if that callback started a request (an idle-time prefetch). A page
200
+ // that polls or streams never settles, so it gives up at `timeoutMs`.
201
+ const settle = async ({ quietMs = 500, timeoutMs = 15_000 } = {}) => {
202
+ const endMs = nowMs() + timeoutMs;
203
+ while (nowMs() < endMs) {
204
+ if (pending.size === 0 && nowMs() - changedMs >= quietMs) {
205
+ const idleFromMs = nowMs();
206
+ await view.evaluate(IDLE);
207
+ if (pending.size === 0 && changedMs < idleFromMs) return;
208
+ }
209
+ await Bun.sleep(25);
210
+ }
211
+ };
212
+ return {
213
+ view,
214
+ browser: "chrome",
215
+ navigate: (url) => view.navigate(url),
216
+ settle,
217
+ close: () => view.close(),
218
+ };
219
+ }
220
+
221
+ function openWebKit(options: PageOptions): Page {
222
+ let view: Bun.WebView;
223
+ try {
224
+ view = new Bun.WebView({ ...VIEWPORT, backend: "webkit" });
225
+ } catch (error) {
226
+ throw openFailed("webkit", error);
227
+ }
228
+ // Each WebKit view has its own HTTP cache, so a fresh view is a cold
229
+ // one, and a second visit in the same view is warm.
230
+ const navigate = async (url: string) => {
231
+ await view.navigate(url);
232
+ await view.evaluate(
233
+ "performance.setResourceTimingBufferSize?.(100000) ?? true",
234
+ );
235
+ if (options.initScript !== undefined) {
236
+ await view.evaluate(`(() => { ${options.initScript} })()`);
237
+ }
238
+ };
239
+ const settle = async ({ quietMs = 500, timeoutMs = 15_000 } = {}) => {
240
+ await view.evaluate(settleInPage(quietMs, timeoutMs));
241
+ };
242
+ return {
243
+ view,
244
+ browser: "webkit",
245
+ navigate,
246
+ settle,
247
+ close: () => view.close(),
248
+ };
249
+ }
250
+
251
+ // Never a reused view, since one keeps fonts and compiled code.
252
+ export function openPage(options: PageOptions): Promise<Page> {
253
+ return options.browser === "chrome"
254
+ ? openChrome(options)
255
+ : Promise.try(() => openWebKit(options));
256
+ }
257
+
258
+ // A person doesn't wait for the network between steps, so only a short
259
+ // settle follows the frame: enough for what the step itself loaded.
260
+ export async function afterInteraction(page: Page): Promise<void> {
261
+ await nextFrame(page.view);
262
+ await page.settle({ quietMs: 150 });
263
+ }
@@ -0,0 +1,48 @@
1
+ import type { Paint } from "./format.ts";
2
+
3
+ // One stderr line, rewritten in place while a browser command runs, so
4
+ // a 10 to 60 second run never looks stuck. main.ts makes one only when
5
+ // stderr is a terminal, not for a coding agent or --json, and clears it
6
+ // before the result prints.
7
+ export interface Progress {
8
+ step(text: string, doneRatio: number): void;
9
+ clear(): void;
10
+ }
11
+
12
+ export const SILENT: Progress = { step: () => {}, clear: () => {} };
13
+
14
+ const BAR_WIDTH = 20;
15
+ const CLEAR_LINE = "\r\x1b[2K";
16
+
17
+ export function createProgress(
18
+ write: (text: string) => void,
19
+ paint: Paint,
20
+ nowMs: () => number,
21
+ ): Progress {
22
+ const startMs = nowMs();
23
+ let text = "";
24
+ let doneRatio = 0;
25
+ const render = () => {
26
+ const done = Math.round(Math.min(1, Math.max(0, doneRatio)) * BAR_WIDTH);
27
+ // Done and to-do differ in shape as well as color, so the bar reads
28
+ // without color too.
29
+ const bar =
30
+ paint.good("━".repeat(done)) + paint.dim("─".repeat(BAR_WIDTH - done));
31
+ const seconds = Math.floor((nowMs() - startMs) / 1000);
32
+ write(`${CLEAR_LINE}${bar} ${text}${paint.dim(` · ${seconds} s`)}`);
33
+ };
34
+ // A tick each second, so the clock moves while a load is in flight.
35
+ const timer = setInterval(render, 1000);
36
+ timer.unref();
37
+ return {
38
+ step(next, ratio) {
39
+ text = next;
40
+ doneRatio = ratio;
41
+ render();
42
+ },
43
+ clear() {
44
+ clearInterval(timer);
45
+ write(CLEAR_LINE);
46
+ },
47
+ };
48
+ }
package/src/serve.ts ADDED
@@ -0,0 +1,58 @@
1
+ import { join, normalize } from "node:path";
2
+
3
+ // compare's server for a build directory, as a host serves one in
4
+ // production: gzip, an ETag, and `max-age=0` so each visit revalidates;
5
+ // with `immutable`, the hashed assets get a year. It's internal: serving
6
+ // a build is deserved's job.
7
+
8
+ const REVALIDATE = "public, max-age=0";
9
+ export const IMMUTABLE = "public, max-age=31536000, immutable";
10
+
11
+ export interface BuildServer {
12
+ url: string;
13
+ stop(): void;
14
+ }
15
+
16
+ // Port 0, a fresh one, so a stale server left on a fixed port can never
17
+ // answer for it.
18
+ export function serveBuild(
19
+ root: string,
20
+ options: { immutable: boolean; assetsPath: string },
21
+ ): BuildServer {
22
+ const server = Bun.serve({
23
+ port: 0,
24
+ async fetch(request) {
25
+ let path = decodeURIComponent(new URL(request.url).pathname);
26
+ if (path.endsWith("/")) path += "index.html";
27
+ const resolved = normalize(join(root, path));
28
+ if (!resolved.startsWith(normalize(root))) {
29
+ return new Response("Not found", { status: 404 });
30
+ }
31
+ const file = Bun.file(resolved);
32
+ if (!(await file.exists())) {
33
+ return new Response("Not found", { status: 404 });
34
+ }
35
+ const bytes = await file.bytes();
36
+ const etag = `"${Bun.hash(bytes).toString(16)}"`;
37
+ const cacheControl =
38
+ options.immutable && path.startsWith(options.assetsPath)
39
+ ? IMMUTABLE
40
+ : REVALIDATE;
41
+ if (request.headers.get("if-none-match") === etag) {
42
+ return new Response(null, {
43
+ status: 304,
44
+ headers: { etag, "cache-control": cacheControl },
45
+ });
46
+ }
47
+ return new Response(Bun.gzipSync(bytes), {
48
+ headers: {
49
+ "content-encoding": "gzip",
50
+ "content-type": file.type,
51
+ "cache-control": cacheControl,
52
+ etag,
53
+ },
54
+ });
55
+ },
56
+ });
57
+ return { url: server.url.href, stop: () => void server.stop(true) };
58
+ }
package/src/stats.ts ADDED
@@ -0,0 +1,37 @@
1
+ // The statistics every command reports: medians, and the run-to-run noise
2
+ // around them as the median absolute deviation.
3
+
4
+ export function median(values: readonly number[]): number {
5
+ const sorted = [...values].sort((a, b) => a - b);
6
+ return sorted[sorted.length >> 1] ?? 0;
7
+ }
8
+
9
+ export function medianAbsoluteDeviation(values: readonly number[]): number {
10
+ const mid = median(values);
11
+ return median(values.map((v) => Math.abs(v - mid)));
12
+ }
13
+
14
+ // A difference inside twice the noise, or under 2% of A, is noise: a
15
+ // same-build comparison read 9 ms faster without the rule. So is one
16
+ // under `resolution`, what the output can show, since a fast page's
17
+ // 0.3 ms otherwise counts as a change at zero noise.
18
+ export function isNoise(
19
+ deltaValue: number,
20
+ noise: number,
21
+ base: number,
22
+ resolution: number,
23
+ ): boolean {
24
+ return (
25
+ Math.abs(deltaValue) < resolution ||
26
+ Math.abs(deltaValue) <= Math.max(2 * noise, 0.02 * Math.abs(base))
27
+ );
28
+ }
29
+
30
+ // A B, B A, A B, …: going second can be systematically faster or slower,
31
+ // so each side goes first in half the rounds.
32
+ export function alternatingOrder(rounds: number): (0 | 1)[] {
33
+ const order: (0 | 1)[] = [];
34
+ for (let i = 0; i < rounds; i++)
35
+ order.push(...(i % 2 ? ([1, 0] as const) : ([0, 1] as const)));
36
+ return order;
37
+ }
package/src/suggest.ts ADDED
@@ -0,0 +1,44 @@
1
+ // "did you mean": the closest of `options` to `input`, if it's close
2
+ // enough to be a typo rather than another word.
3
+
4
+ function distance(a: string, b: string): number {
5
+ let previous = Array.from({ length: b.length + 1 }, (_, i) => i);
6
+ for (let i = 1; i <= a.length; i++) {
7
+ const current = [i];
8
+ for (let j = 1; j <= b.length; j++) {
9
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
10
+ current[j] = Math.min(
11
+ (previous[j] ?? 0) + 1,
12
+ (current[j - 1] ?? 0) + 1,
13
+ (previous[j - 1] ?? 0) + cost,
14
+ );
15
+ }
16
+ previous = current;
17
+ }
18
+ return previous[b.length] ?? 0;
19
+ }
20
+
21
+ function findClosest(
22
+ input: string,
23
+ options: readonly string[],
24
+ ): string | undefined {
25
+ let best: string | undefined;
26
+ let bestDistance = Math.max(2, Math.floor(input.length / 3)) + 1;
27
+ for (const option of options) {
28
+ const d = distance(input, option);
29
+ if (d < bestDistance) {
30
+ best = option;
31
+ bestDistance = d;
32
+ }
33
+ }
34
+ return best;
35
+ }
36
+
37
+ export function didYouMean(
38
+ input: string,
39
+ options: readonly string[],
40
+ quote: (option: string) => string = (option) => option,
41
+ ): string {
42
+ const closest = findClosest(input, options);
43
+ return closest === undefined ? "" : ` (did you mean ${quote(closest)}?)`;
44
+ }