trivium 0.0.0 → 0.1.1

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,398 @@
1
+ import { nowMs } from "./env.ts";
2
+ import { TriviumError } from "./errors.ts";
3
+ import {
4
+ aligned,
5
+ closingLine,
6
+ elapsed,
7
+ headerRow,
8
+ ms,
9
+ NOTE_INDENT,
10
+ type Outcome,
11
+ type Paint,
12
+ paintRating,
13
+ plural,
14
+ ratingLabel,
15
+ SCHEMA_VERSION,
16
+ SEPARATOR,
17
+ truncateWords,
18
+ withGutter,
19
+ withNotes,
20
+ } from "./format.ts";
21
+ import type { ResolvedConfig } from "./load-config.ts";
22
+ import { contextLine, throttleLabel } from "./load.ts";
23
+ import {
24
+ afterInteraction,
25
+ type Browser,
26
+ openPage,
27
+ type Throttle,
28
+ waitFor,
29
+ } from "./page.ts";
30
+ import type { Progress } from "./progress.ts";
31
+ import { median, medianAbsoluteDeviation } from "./stats.ts";
32
+ import { ratingOf, readyExpression, readyName } from "./vitals.ts";
33
+
34
+ // Event Timing reports no event under 16 ms, so 0 means "too quick to
35
+ // be reported", never "instant".
36
+ const EVENT_THRESHOLD_MS = 16;
37
+ // A step label's width in the human format, so the table fits 80
38
+ // columns; the config and --json keep it whole.
39
+ const LABEL_MAX = 32;
40
+ const latency = (valueMs: number) =>
41
+ valueMs < EVENT_THRESHOLD_MS ? `<${EVENT_THRESHOLD_MS} ms` : ms(valueMs);
42
+
43
+ // Noise needs two runs, and a value too quick to report has none.
44
+ const withNoise = (valueMs: number, noiseMs: number, runs: number) =>
45
+ runs < 2 || valueMs < EVENT_THRESHOLD_MS
46
+ ? latency(valueMs)
47
+ : `${latency(valueMs)} ±${ms(noiseMs)}`;
48
+
49
+ interface InteractionsInput {
50
+ url: string;
51
+ config: ResolvedConfig;
52
+ browser: Browser;
53
+ throttle: Throttle;
54
+ runs: number;
55
+ // Start at the ready mark instead of once the page settles. INP doesn't
56
+ // count waiting for a lazy chunk, so an early click can score better
57
+ // while showing a spinner: the loader column shows it.
58
+ early: boolean;
59
+ progress: Progress;
60
+ }
61
+
62
+ // Latency per interaction is the longest Event Timing entry sharing its
63
+ // interactionId, since one input fires several events. Every layout shift
64
+ // counts, input-driven ones too: CLS skips those within 500 ms of input,
65
+ // but content that jumps after a click still jumped.
66
+ const observer = (loaders: readonly string[]) => `
67
+ window.__interactions = new Map();
68
+ try {
69
+ new PerformanceObserver((list) => {
70
+ for (const e of list.getEntries()) {
71
+ if (!e.interactionId) continue;
72
+ const prev = window.__interactions.get(e.interactionId);
73
+ if (!prev || e.duration > prev.duration) window.__interactions.set(e.interactionId, { start: e.startTime, duration: e.duration });
74
+ }
75
+ }).observe({ type: "event", durationThreshold: ${EVENT_THRESHOLD_MS}, buffered: true });
76
+ } catch {}
77
+ window.__shifts = [];
78
+ // The nearest element with an id or class: a moved text node names its line's container.
79
+ // Without one within four levels, the element itself, by tag.
80
+ const label = (n) => {
81
+ const start = n?.nodeType === 1 ? n : n?.parentElement;
82
+ let el = start;
83
+ for (let up = 0; el && !el.id && !el.classList.length && up < 4; up++) el = el.parentElement;
84
+ if (!el || (!el.id && !el.classList.length)) el = start;
85
+ if (!el) return "?";
86
+ const name = el.id ? "#" + el.id : el.classList.length ? "." + el.classList[0] : "";
87
+ return el.localName + name + (n.nodeType === 3 ? " (text)" : "");
88
+ };
89
+ const area = (s) => s.previousRect.width * s.previousRect.height;
90
+ try {
91
+ new PerformanceObserver((list) => {
92
+ for (const e of list.getEntries()) {
93
+ const moved = [...e.sources].sort((a, b) => area(b) - area(a))[0];
94
+ // A node removed since has no element: describe its box instead.
95
+ const where = moved?.node ? label(moved.node) : moved
96
+ ? "(removed) " + Math.round(moved.previousRect.width) + "x" + Math.round(moved.previousRect.height) + " at y " + Math.round(moved.previousRect.y) + " → " + Math.round(moved.currentRect.y)
97
+ : "?";
98
+ window.__shifts.push([e.startTime, e.value, where]);
99
+ }
100
+ }).observe({ type: "layout-shift", buffered: true });
101
+ } catch {}
102
+ window.__loaders = { spans: [], since: null };
103
+ const selectors = ${JSON.stringify(loaders)};
104
+ if (selectors.length) {
105
+ const l = window.__loaders;
106
+ const shown = () => selectors.some((s) => [...document.querySelectorAll(s)].some((el) => el.getClientRects().length > 0));
107
+ const update = () => {
108
+ const on = shown();
109
+ if (on && l.since === null) l.since = performance.now();
110
+ else if (!on && l.since !== null) { l.spans.push([l.since, performance.now()]); l.since = null; }
111
+ };
112
+ new MutationObserver(update).observe(document, { subtree: true, childList: true, attributes: true, attributeFilter: ["class", "style", "hidden", "aria-busy"] });
113
+ update();
114
+ }
115
+ `;
116
+
117
+ const COLLECT = `(() => {
118
+ const l = window.__loaders;
119
+ const now = performance.now();
120
+ return {
121
+ entries: [...window.__interactions.values()],
122
+ shifts: window.__shifts,
123
+ spans: l.since === null ? l.spans : [...l.spans, [l.since, now]],
124
+ now,
125
+ };
126
+ })()`;
127
+
128
+ interface Collected {
129
+ entries: { start: number; duration: number }[];
130
+ shifts: [number, number, string][];
131
+ spans: [number, number][];
132
+ now: number;
133
+ }
134
+
135
+ // Entries arrive after the next step starts, so each is matched to the
136
+ // step whose input came before it, once all are in: read per step, a
137
+ // late entry counts for the next one.
138
+ export function assignToSteps<T>(
139
+ items: readonly T[],
140
+ timeOf: (item: T) => number,
141
+ startsMs: readonly number[],
142
+ endMs: number,
143
+ ): T[][] {
144
+ return startsMs.map((from, i) => {
145
+ const to = startsMs[i + 1] ?? endMs;
146
+ return items.filter((item) => timeOf(item) >= from && timeOf(item) < to);
147
+ });
148
+ }
149
+
150
+ const overlapMs = (
151
+ spans: readonly [number, number][],
152
+ from: number,
153
+ to: number,
154
+ ): number =>
155
+ spans.reduce(
156
+ (sum, [a, b]) => sum + Math.max(0, Math.min(b, to) - Math.max(a, from)),
157
+ 0,
158
+ );
159
+
160
+ interface StepRun {
161
+ latencyMs: number;
162
+ loaderMs: number;
163
+ shift: number;
164
+ movers: [string, number][];
165
+ }
166
+
167
+ async function runOnce(input: InteractionsInput): Promise<{
168
+ steps: StepRun[];
169
+ inpMs: number;
170
+ loaderBeforeFirstMs: number;
171
+ }> {
172
+ const page = await openPage({
173
+ browser: input.browser,
174
+ throttle: input.throttle,
175
+ initScript: observer(input.config.loaders),
176
+ });
177
+ try {
178
+ await page.navigate(input.url);
179
+ await waitFor(
180
+ page.view,
181
+ readyExpression(input.config),
182
+ readyName(input.config),
183
+ );
184
+ // Like a person reading first, while idle-time work settles.
185
+ if (!input.early) await page.settle();
186
+ const startsMs: number[] = [];
187
+ for (const step of input.config.steps) {
188
+ startsMs.push(await page.view.evaluate<number>("performance.now()"));
189
+ try {
190
+ await step.run(page.view);
191
+ } catch (error) {
192
+ const message = error instanceof Error ? error.message : String(error);
193
+ throw new TriviumError(
194
+ "TV_CONFIG",
195
+ `trivium interactions: step ${JSON.stringify(step.label)} failed: ${message}: check its selector in the config`,
196
+ { cause: error },
197
+ );
198
+ }
199
+ await afterInteraction(page);
200
+ }
201
+ await page.settle({ quietMs: 300 });
202
+ const r = await page.view.evaluate<Collected>(COLLECT);
203
+ const entries = assignToSteps(r.entries, (e) => e.start, startsMs, r.now);
204
+ const shifts = assignToSteps(r.shifts, ([t]) => t, startsMs, r.now);
205
+ const steps = startsMs.map((from, i): StepRun => {
206
+ const to = startsMs[i + 1] ?? r.now;
207
+ const durations = (entries[i] ?? []).map((e) => e.duration);
208
+ const inStep = shifts[i] ?? [];
209
+ return {
210
+ latencyMs: durations.length ? Math.max(...durations) : 0,
211
+ loaderMs: overlapMs(r.spans, from, to),
212
+ shift: inStep.reduce((sum, [, v]) => sum + v, 0),
213
+ movers: inStep.map(([, v, where]) => [where, v]),
214
+ };
215
+ });
216
+ return {
217
+ steps,
218
+ // Under 50 interactions, INP is the worst one.
219
+ inpMs: r.entries.length
220
+ ? Math.max(...r.entries.map((e) => e.duration))
221
+ : 0,
222
+ loaderBeforeFirstMs: overlapMs(r.spans, 0, startsMs[0] ?? r.now),
223
+ };
224
+ } finally {
225
+ page.close();
226
+ }
227
+ }
228
+
229
+ export async function runInteractions(
230
+ input: InteractionsInput,
231
+ ): Promise<Outcome> {
232
+ if (input.config.steps.length === 0) {
233
+ throw new TriviumError(
234
+ "TV_CONFIG",
235
+ `trivium interactions: no steps to run: add steps to ${input.config.file ?? "trivium.config.ts"}`,
236
+ );
237
+ }
238
+ const startMs = nowMs();
239
+ const runs: Awaited<ReturnType<typeof runOnce>>[] = [];
240
+ for (let i = 0; i < input.runs; i++) {
241
+ input.progress.step(
242
+ `run ${i + 1} of ${input.runs}${i === 0 ? ", starting the browser" : `${SEPARATOR}${plural(input.config.steps.length, "step")} each`}`,
243
+ i / input.runs,
244
+ );
245
+ runs.push(await runOnce(input));
246
+ }
247
+ const shiftsMeasured = input.browser === "chrome";
248
+ const loadersSet = input.config.loaders.length > 0;
249
+ const steps = input.config.steps.map((step, i) => {
250
+ const each = runs.flatMap((run) => run.steps[i] ?? []);
251
+ const moved = new Map<string, number>();
252
+ for (const run of each) {
253
+ for (const [where, v] of run.movers) {
254
+ moved.set(where, (moved.get(where) ?? 0) + v / input.runs);
255
+ }
256
+ }
257
+ const [top] = [...moved].sort((a, b) => b[1] - a[1]);
258
+ const latencies = each.map((s) => s.latencyMs);
259
+ return {
260
+ label: step.label,
261
+ latencyMs: median(latencies),
262
+ latencyNoiseMs: medianAbsoluteDeviation(latencies),
263
+ loaderMs: loadersSet ? median(each.map((s) => s.loaderMs)) : null,
264
+ shift: shiftsMeasured ? median(each.map((s) => s.shift)) : null,
265
+ movedMost:
266
+ shiftsMeasured && top && top[1] >= 0.01
267
+ ? { element: top[0], shift: top[1] }
268
+ : null,
269
+ };
270
+ });
271
+ const inps = runs.map((r) => r.inpMs);
272
+ const inpMs = median(inps);
273
+ const inpNoiseMs = medianAbsoluteDeviation(inps);
274
+ const inpRating = ratingOf("inp", inpMs) ?? "good";
275
+ const loaderBeforeFirstMs = loadersSet
276
+ ? median(runs.map((r) => r.loaderBeforeFirstMs))
277
+ : null;
278
+ const elapsedMs = nowMs() - startMs;
279
+ const headerOf = (paint: Paint, human: boolean) =>
280
+ [
281
+ `INP ${withNoise(inpMs, inpNoiseMs, input.runs)} ${paintRating(paint, inpRating)(human ? ratingLabel(inpRating) : inpRating)}${SEPARATOR}${plural(steps.length, "step")}`,
282
+ paint.dim(
283
+ contextLine([
284
+ input.url,
285
+ input.browser,
286
+ throttleLabel(input.throttle),
287
+ input.early ? "from the ready mark" : "",
288
+ `median of ${plural(input.runs, "run")}`,
289
+ ]),
290
+ ),
291
+ ].join("\n");
292
+ return {
293
+ exitCode: 0,
294
+ json: {
295
+ schemaVersion: SCHEMA_VERSION,
296
+ ok: true,
297
+ command: "interactions",
298
+ url: input.url,
299
+ browser: input.browser,
300
+ throttle: input.throttle,
301
+ early: input.early,
302
+ runs: input.runs,
303
+ config: input.config.file ?? null,
304
+ inpMs,
305
+ inpNoiseMs,
306
+ inpRating,
307
+ loaderBeforeFirstMs,
308
+ steps,
309
+ elapsedMs,
310
+ ...(!shiftsMeasured && {
311
+ unavailable: { shift: "WebKit reports no layout-shift entries" },
312
+ }),
313
+ },
314
+ text(format, paint) {
315
+ const header = headerOf(paint, format === "human");
316
+ // Noise is its own column, so latencies line up on their units.
317
+ const noisy = input.runs >= 2;
318
+ const head = ["step", "latency"];
319
+ if (noisy) head.push("noise");
320
+ if (loadersSet) head.push("loader");
321
+ if (shiftsMeasured) head.push("shift");
322
+ const rows = [headerRow(paint, head)];
323
+ // A moved-most note goes under its step, so it can't widen the
324
+ // step column.
325
+ const below = new Map<number, string[]>();
326
+ // Only a step slower than INP's good threshold is marked, since it's
327
+ // the one to fix.
328
+ const marks = new Map<number, (text: string) => string>();
329
+ for (const s of steps) {
330
+ const stepRating = ratingOf("inp", s.latencyMs);
331
+ if (stepRating !== undefined && stepRating !== "good") {
332
+ marks.set(rows.length, paintRating(paint, stepRating));
333
+ }
334
+ if (s.movedMost) {
335
+ below.set(rows.length, [
336
+ `${NOTE_INDENT}${paint.dim(`└ ${s.movedMost.element} moved most (${s.movedMost.shift.toFixed(3)})`)}`,
337
+ ]);
338
+ }
339
+ const row = [truncateWords(s.label, LABEL_MAX), latency(s.latencyMs)];
340
+ if (noisy) {
341
+ row.push(
342
+ s.latencyMs < EVENT_THRESHOLD_MS
343
+ ? ""
344
+ : paint.dim(`±${ms(s.latencyNoiseMs)}`),
345
+ );
346
+ }
347
+ if (s.loaderMs !== null) row.push(ms(s.loaderMs));
348
+ if (s.shift !== null) row.push(s.shift.toFixed(3));
349
+ rows.push(row);
350
+ }
351
+ const moved = steps.flatMap((s) =>
352
+ s.movedMost
353
+ ? [
354
+ `${s.label}: ${s.movedMost.element} moved most (${s.movedMost.shift.toFixed(3)})`,
355
+ ]
356
+ : [],
357
+ );
358
+ const notes: string[] = [];
359
+ if (loaderBeforeFirstMs !== null && loaderBeforeFirstMs > 0) {
360
+ notes.push(`loader before the first step: ${ms(loaderBeforeFirstMs)}`);
361
+ }
362
+ if (!shiftsMeasured)
363
+ notes.push(
364
+ paint.dim("shift: n/a, WebKit reports no layout-shift entries"),
365
+ );
366
+ if (format === "agent") {
367
+ return [
368
+ header,
369
+ ...steps.map(
370
+ (st) =>
371
+ `${st.label}: latency ${withNoise(st.latencyMs, st.latencyNoiseMs, input.runs)}${st.loaderMs === null ? "" : `, loader ${ms(st.loaderMs)}`}${st.shift === null ? "" : `, shift ${st.shift.toFixed(3)}`}`,
372
+ ),
373
+ ...moved,
374
+ ...notes,
375
+ ].join("\n");
376
+ }
377
+ const numeric = head.map((_, i) => i).slice(1);
378
+ return [
379
+ header,
380
+ "",
381
+ ...withNotes(withGutter(aligned(rows, numeric), marks), below),
382
+ ...(notes.length > 0 ? ["", ...notes.map((n) => ` ${n}`)] : []),
383
+ "",
384
+ inpRating === "good"
385
+ ? closingLine(
386
+ paint,
387
+ "Steps pass",
388
+ `measured in ${elapsed(elapsedMs)}${SEPARATOR}${plural(input.runs, "run")}`,
389
+ )
390
+ : closingLine(
391
+ paint,
392
+ `measured in ${elapsed(elapsedMs)}`,
393
+ `${plural(input.runs, "run")} of ${plural(steps.length, "step")}`,
394
+ ),
395
+ ].join("\n");
396
+ },
397
+ };
398
+ }
@@ -0,0 +1,208 @@
1
+ import { existsSync } from "node:fs";
2
+ import { dirname, join, relative, resolve } from "node:path";
3
+
4
+ import type { Step } from "./config.ts";
5
+ import { TriviumError } from "./errors.ts";
6
+ import { didYouMean } from "./suggest.ts";
7
+
8
+ const NAMES = ["trivium.config.ts", "trivium.config.json"];
9
+ const KEYS = ["url", "readyMark", "assets", "steps", "element", "loaders"];
10
+ const ASSET_KEYS = ["path", "hash"];
11
+ const ELEMENT_KEYS = ["label", "selector"];
12
+ const STEP_KEYS = ["label", "run"];
13
+
14
+ // Vite's `name-[hash].ext`, an 8-character hash, so a Vite build needs
15
+ // no setting.
16
+ const DEFAULT_HASH = /-[\w-]{8}(?=\.\w+$)/;
17
+
18
+ export interface ResolvedConfig {
19
+ // Where it came from, relative to the working directory; undefined when
20
+ // no file was found, so everything is a default.
21
+ file: string | undefined;
22
+ url: string | undefined;
23
+ readyMark: string | undefined;
24
+ assets: { path: string; hash: RegExp };
25
+ steps: readonly Step[];
26
+ element: { label: string; selector: string } | undefined;
27
+ loaders: readonly string[];
28
+ }
29
+
30
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
31
+ typeof value === "object" && value !== null && !Array.isArray(value);
32
+
33
+ const isStepRun = (value: unknown): value is Step["run"] =>
34
+ typeof value === "function";
35
+
36
+ // Like git finding its root: the first directory up from `from` with a
37
+ // config, stopping at a package.json so another project's never applies.
38
+ export function findConfig(from: string): string | undefined {
39
+ for (let dir = resolve(from); ; dir = dirname(dir)) {
40
+ for (const name of NAMES) {
41
+ const path = join(dir, name);
42
+ if (existsSync(path)) return path;
43
+ }
44
+ if (existsSync(join(dir, "package.json")) || dirname(dir) === dir) {
45
+ return undefined;
46
+ }
47
+ }
48
+ }
49
+
50
+ function unknownKeys(
51
+ where: string,
52
+ value: Record<string, unknown>,
53
+ known: readonly string[],
54
+ problems: string[],
55
+ ): void {
56
+ for (const key of Object.keys(value)) {
57
+ if (!known.includes(key)) {
58
+ problems.push(
59
+ `${where}unknown key "${key}"${didYouMean(key, known, (k) => `"${k}"`)}`,
60
+ );
61
+ }
62
+ }
63
+ }
64
+
65
+ function optionalString(
66
+ value: Record<string, unknown>,
67
+ key: string,
68
+ where: string,
69
+ problems: string[],
70
+ ): string | undefined {
71
+ const found = value[key];
72
+ if (found === undefined) return undefined;
73
+ if (typeof found === "string" && found !== "") return found;
74
+ problems.push(`${where}${key}: expected a non-empty string`);
75
+ return undefined;
76
+ }
77
+
78
+ // Checks what the editor can't: a `.json` config, and computed values.
79
+ // Every problem at once (config.md, Validation).
80
+ export function parseConfig(
81
+ raw: unknown,
82
+ file: string | undefined,
83
+ ): ResolvedConfig {
84
+ const problems: string[] = [];
85
+ const config = isRecord(raw) ? raw : {};
86
+ if (!isRecord(raw)) problems.push("expected an object as the default export");
87
+ unknownKeys("", config, KEYS, problems);
88
+
89
+ const url = optionalString(config, "url", "", problems);
90
+ const readyMark = optionalString(config, "readyMark", "", problems);
91
+
92
+ let assets = { path: "/assets/", hash: DEFAULT_HASH };
93
+ if (config.assets !== undefined) {
94
+ if (isRecord(config.assets)) {
95
+ unknownKeys("assets.", config.assets, ASSET_KEYS, problems);
96
+ const path = optionalString(config.assets, "path", "assets.", problems);
97
+ const hash = config.assets.hash;
98
+ let pattern = DEFAULT_HASH;
99
+ if (hash instanceof RegExp) pattern = hash;
100
+ else if (typeof hash === "string") pattern = new RegExp(hash);
101
+ else if (hash !== undefined) {
102
+ problems.push(
103
+ "assets.hash: expected a RegExp, or its source as a string",
104
+ );
105
+ }
106
+ assets = { path: path ?? assets.path, hash: pattern };
107
+ } else problems.push("assets: expected an object with path and hash");
108
+ }
109
+
110
+ const steps: Step[] = [];
111
+ if (config.steps !== undefined) {
112
+ if (Array.isArray(config.steps)) {
113
+ for (const [i, step] of config.steps.entries()) {
114
+ const where = `steps[${i}].`;
115
+ if (!isRecord(step)) {
116
+ problems.push(`steps[${i}]: expected { label, run }`);
117
+ continue;
118
+ }
119
+ unknownKeys(where, step, STEP_KEYS, problems);
120
+ const label = optionalString(step, "label", where, problems);
121
+ if (label === undefined && step.label === undefined) {
122
+ problems.push(`${where}label: missing`);
123
+ }
124
+ if (!isStepRun(step.run)) {
125
+ problems.push(`${where}run: expected a function of the view`);
126
+ } else if (label !== undefined) steps.push({ label, run: step.run });
127
+ }
128
+ } else problems.push("steps: expected a list of { label, run }");
129
+ }
130
+
131
+ let element: ResolvedConfig["element"];
132
+ if (config.element !== undefined) {
133
+ if (isRecord(config.element)) {
134
+ unknownKeys("element.", config.element, ELEMENT_KEYS, problems);
135
+ const label = optionalString(
136
+ config.element,
137
+ "label",
138
+ "element.",
139
+ problems,
140
+ );
141
+ const selector = optionalString(
142
+ config.element,
143
+ "selector",
144
+ "element.",
145
+ problems,
146
+ );
147
+ if (label !== undefined && selector !== undefined) {
148
+ element = { label, selector };
149
+ } else if (label === undefined && selector === undefined) {
150
+ problems.push("element: expected { label, selector }");
151
+ }
152
+ } else problems.push("element: expected { label, selector }");
153
+ }
154
+
155
+ const loaders: string[] = [];
156
+ if (config.loaders !== undefined) {
157
+ if (
158
+ Array.isArray(config.loaders) &&
159
+ config.loaders.every((s) => typeof s === "string" && s !== "")
160
+ ) {
161
+ for (const selector of config.loaders) {
162
+ if (typeof selector === "string") loaders.push(selector);
163
+ }
164
+ } else problems.push("loaders: expected a list of CSS selectors");
165
+ }
166
+
167
+ if (problems.length > 0) {
168
+ const name = file ?? "config";
169
+ throw new TriviumError(
170
+ "TV_CONFIG",
171
+ `trivium config: ${name}: ${problems.join(`; ${name}: `)}`,
172
+ );
173
+ }
174
+ return { file, url, readyMark, assets, steps, element, loaders };
175
+ }
176
+
177
+ // The config `--config` names, else the one found from `cwd`, else none.
178
+ export async function loadConfig(
179
+ explicit: string | undefined,
180
+ cwd: string,
181
+ ): Promise<ResolvedConfig> {
182
+ const path =
183
+ explicit === undefined ? findConfig(cwd) : resolve(cwd, explicit);
184
+ if (path === undefined) return parseConfig({}, undefined);
185
+ const shown = relative(cwd, path) || path;
186
+ if (!existsSync(path)) {
187
+ throw new TriviumError(
188
+ "TV_CONFIG",
189
+ `trivium config: no file at ${shown}: check the --config path`,
190
+ );
191
+ }
192
+ let raw: unknown;
193
+ try {
194
+ if (path.endsWith(".json")) raw = await Bun.file(path).json();
195
+ else {
196
+ const module: unknown = await import(path);
197
+ raw = isRecord(module) ? module.default : undefined;
198
+ }
199
+ } catch (error) {
200
+ const message = error instanceof Error ? error.message : String(error);
201
+ throw new TriviumError(
202
+ "TV_CONFIG",
203
+ `trivium config: ${shown} didn't load: ${message}`,
204
+ { cause: error },
205
+ );
206
+ }
207
+ return parseConfig(raw, shown);
208
+ }