ostia 0.2.12 → 0.3.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.
Files changed (98) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -358
  3. package/docs/agent-protocol.md +210 -0
  4. package/docs/cli.md +1196 -0
  5. package/docs/config.md +233 -0
  6. package/docs/document-schema.md +224 -0
  7. package/docs/library.md +421 -0
  8. package/docs/preload-recipes.md +169 -0
  9. package/docs/statistics.md +218 -0
  10. package/index.d.ts +923 -679
  11. package/package.json +16 -14
  12. package/src/ab/ab-runner.ts +487 -0
  13. package/src/ab/index.ts +1160 -0
  14. package/src/baseline/index.ts +69 -0
  15. package/src/bench/index.ts +516 -0
  16. package/src/bench/projects.ts +43 -0
  17. package/src/bench/range.ts +27 -0
  18. package/src/bench/registry.ts +426 -0
  19. package/src/bench/run-tasks.ts +179 -0
  20. package/src/bench/run.ts +52 -0
  21. package/src/bench/runner.ts +162 -0
  22. package/src/bench/support.ts +161 -0
  23. package/src/bench/sweep.ts +41 -0
  24. package/src/cache/fingerprint.ts +62 -0
  25. package/src/cache/store.ts +40 -0
  26. package/src/capture/bunflags.ts +92 -0
  27. package/src/capture/cpu-parse.ts +131 -0
  28. package/src/capture/cpu.ts +47 -0
  29. package/src/capture/frames.ts +60 -0
  30. package/src/capture/heap-parse.ts +111 -0
  31. package/src/capture/heap.ts +36 -0
  32. package/src/capture/inspector.ts +47 -0
  33. package/src/capture/jsc-parse.ts +167 -0
  34. package/src/capture/jsc.ts +35 -0
  35. package/src/capture/sampling.ts +5 -0
  36. package/src/ci/index.ts +440 -0
  37. package/src/cli/flags.ts +263 -0
  38. package/{chunk-9sx15b08.js → src/cli/help.ts} +23 -11
  39. package/src/cli/main.ts +18 -0
  40. package/src/cli/output.ts +179 -0
  41. package/src/cli/run.ts +1110 -0
  42. package/src/compare/index.ts +624 -0
  43. package/src/config/env.ts +13 -0
  44. package/src/config/index.ts +283 -0
  45. package/src/config/validate.ts +273 -0
  46. package/src/errors.ts +8 -0
  47. package/src/format.ts +35 -0
  48. package/src/glob.ts +45 -0
  49. package/src/index.ts +60 -0
  50. package/src/ir/cpu.ts +10 -0
  51. package/src/ir/defined.ts +12 -0
  52. package/src/ir/document.ts +491 -0
  53. package/src/ir/fp.ts +28 -0
  54. package/src/ir/git.ts +37 -0
  55. package/src/ir/types.ts +615 -0
  56. package/src/measure/alloc.ts +56 -0
  57. package/src/measure/cpu.ts +91 -0
  58. package/src/measure/environment.ts +38 -0
  59. package/src/measure/inprocess.ts +191 -0
  60. package/src/measure/instructions.ts +139 -0
  61. package/src/measure/loop.ts +64 -0
  62. package/src/measure/noise.ts +55 -0
  63. package/src/measure/paired.ts +304 -0
  64. package/src/measure/peak.ts +201 -0
  65. package/src/measure/timing.ts +263 -0
  66. package/src/profile.ts +110 -0
  67. package/src/renderers/collapsed.ts +42 -0
  68. package/src/renderers/cpu-tree.ts +191 -0
  69. package/src/renderers/cpuprofile.ts +43 -0
  70. package/src/renderers/format.ts +132 -0
  71. package/src/renderers/index.ts +37 -0
  72. package/src/renderers/json.ts +10 -0
  73. package/src/renderers/jsonl.ts +19 -0
  74. package/src/renderers/markdown.ts +543 -0
  75. package/src/renderers/mermaid.ts +90 -0
  76. package/src/renderers/minimal.ts +602 -0
  77. package/src/renderers/paired.ts +223 -0
  78. package/src/renderers/relative.ts +60 -0
  79. package/src/renderers/select.ts +264 -0
  80. package/src/renderers/speedscope.ts +73 -0
  81. package/src/renderers/terminal.ts +470 -0
  82. package/src/renderers/types.ts +27 -0
  83. package/src/spawn/index.ts +387 -0
  84. package/src/stats/bootstrap.ts +151 -0
  85. package/src/stats/index.ts +144 -0
  86. package/src/stats/mannwhitney.ts +82 -0
  87. package/src/time.ts +337 -0
  88. package/src/version.ts +3 -0
  89. package/ab-runner.ts +0 -8
  90. package/chunk-05jfst35.js +0 -28
  91. package/chunk-1g1x9zz2.js +0 -15
  92. package/chunk-23g2rwrn.js +0 -3
  93. package/chunk-468h5412.js +0 -25
  94. package/chunk-4esjfc2m.js +0 -2
  95. package/chunk-ct2xsezd.js +0 -14
  96. package/cli.js +0 -3
  97. package/index.js +0 -2
  98. package/runner.ts +0 -7
@@ -0,0 +1,283 @@
1
+ import { DEFAULT_THRESHOLDS, type Thresholds } from "../compare/index.ts";
2
+ import { errorMessage } from "../errors.ts";
3
+ import type { PrepareHook, TimeSource } from "../spawn/index.ts";
4
+ import { ConfigError, validateConfig } from "./validate.ts";
5
+
6
+ export { ConfigError };
7
+
8
+ /**
9
+ * Exactly one of `command` (a subprocess to time) / `suites` (in-process
10
+ * `group()`/`task()` suite file globs, run via `bench()`, each task gated
11
+ * individually) must be given. */
12
+ export interface WorkloadConfig {
13
+ label?: string;
14
+ command?: string[];
15
+ suites?: string[];
16
+ /**
17
+ * `command` only. Globs of the files the timing depends on: `ostia ci`
18
+ * reuses a cached run while their contents are unchanged. Omitted, the
19
+ * workload always reruns; `[]` caches until the command or config changes.
20
+ * */
21
+ inputs?: string[];
22
+ /**
23
+ * `command` only. Runs before every trial (warmup included), unmeasured:
24
+ * a command string / argv array, or in `ostia.config.ts` a function. A
25
+ * function makes the workload uncacheable for `ostia ci`. */
26
+ prepare?: PrepareHook;
27
+ /**
28
+ * `command` only. Take timing from a number in the command's own output
29
+ * instead of its wall clock; see `TimeSource`. */
30
+ timeSource?: TimeSource;
31
+ /**
32
+ * `command`: kills a trial (or prepare hook) after this many ms.
33
+ * `suites`: kills a suite file's (or isolated task's) process after this
34
+ * many ms, overriding `bench.timeoutMs`. Overrides `ostia ci`'s 10-minute
35
+ * default. */
36
+ timeoutMs?: number;
37
+ /**
38
+ * `command` only. Exit codes to treat as success; see
39
+ * `TimeOptions.ignoreExitCodes`. */
40
+ ignoreExitCodes?: number[];
41
+ }
42
+
43
+ /**
44
+ * Launch settings for the suite files matching `suites`; see
45
+ * `BenchOptions.projects`. */
46
+ export interface BenchProject {
47
+ /**
48
+ * Globs against the current directory. A suite file takes the first
49
+ * project one of these matches; `ostia bench` with no files also runs
50
+ * every file they expand to. */
51
+ suites: string[];
52
+ /**
53
+ * Replaces the top-level `preload` for these files; `[]` runs them with
54
+ * none. Unset: the top-level list applies. */
55
+ preload?: string[];
56
+ /** Replaces the top-level `bunFlags` for these files, as `preload` does. */
57
+ bunFlags?: string[];
58
+ }
59
+
60
+ export interface BenchConfig {
61
+ /**
62
+ * Suite file globs, resolved against the config's directory (e.g.
63
+ * "bench/**\/*.bench.ts"). Suite files given on the command line replace
64
+ * this list. */
65
+ suites?: string[];
66
+ /**
67
+ * Per-suite `preload`/`bunFlags`, so one tier (e.g. DOM-dependent suites)
68
+ * can pay for a setup the others don't need. The first project whose
69
+ * `suites` match a file wins; a file no project matches gets the top-level
70
+ * `preload`/`bunFlags`. `--preload` / `--bun-flags` replace the matching
71
+ * field for every file. */
72
+ projects?: BenchProject[];
73
+ preload?: string[];
74
+ /**
75
+ * Extra flags for the `bun` process that runs each suite file; see
76
+ * `BenchOptions.bunFlags`. `--bun-flags` replaces this list. */
77
+ bunFlags?: string[];
78
+ jobs?: number | "auto";
79
+ budgetMs?: number;
80
+ samples?: number;
81
+ minSamples?: number;
82
+ gc?: boolean;
83
+ cpu?: boolean;
84
+ cpuIntervalUs?: number;
85
+ alloc?: boolean;
86
+ peakMem?: boolean;
87
+ filter?: string;
88
+ isolate?: boolean;
89
+ outDir?: string;
90
+ /**
91
+ * Kills a suite file's (or isolated task's) subprocess after this many
92
+ * ms; overrides `ostia ci`'s 10-minute default. */
93
+ timeoutMs?: number;
94
+ }
95
+
96
+ /**
97
+ * Settings for `ostia ab` only; it reads the rest (suites, filter,
98
+ * preload, ...) from `bench`. */
99
+ export interface AbConfig {
100
+ /**
101
+ * Shell command(s) run once in a freshly extracted base tree, e.g. to
102
+ * build gitignored files the suites import; see `AbOptions.baseSetup`.
103
+ * `--base-setup` replaces this list. */
104
+ setup?: string | string[];
105
+ /**
106
+ * Base trees to keep cached; see `AbOptions.keepTrees`. `--keep-trees`
107
+ * overrides. Default: 5. */
108
+ keepTrees?: number;
109
+ /**
110
+ * Judge rounds by `"time"` or `"instructions"`; see `AbOptions.metric`.
111
+ * `--metric` overrides. Default: `"time"`. */
112
+ metric?: "time" | "instructions";
113
+ /**
114
+ * Compare retained heap per call; see `AbOptions.alloc`. `--alloc` /
115
+ * `--no-alloc` override. `bench.alloc` doesn't apply to `ab`. */
116
+ alloc?: boolean;
117
+ /**
118
+ * Compare peak RSS of the first call; see `AbOptions.peakMem`.
119
+ * `--peak-mem` / `--no-peak-mem` override. `bench.peakMem` doesn't apply
120
+ * to `ab`. */
121
+ peakMem?: boolean;
122
+ /**
123
+ * Memory verdict threshold, percent; see `AbOptions.memThresholdPct`.
124
+ * `--mem-threshold` overrides. Default: 10. */
125
+ memThresholdPct?: number;
126
+ }
127
+
128
+ export interface OstiaConfig {
129
+ /** `command` workloads: exact trial count; see `time()`. */
130
+ samples?: number;
131
+ /** `command` workloads: sampling budget in ms; see `time()`. */
132
+ budgetMs?: number;
133
+ /** `command` workloads: floor on trials; see `time()`. */
134
+ minSamples?: number;
135
+ warmup: number;
136
+ outDir: string;
137
+ baselineDir: string;
138
+ baseline: string;
139
+ thresholds: Thresholds;
140
+ workloads: WorkloadConfig[];
141
+ bench?: BenchConfig;
142
+ ab?: AbConfig;
143
+ /**
144
+ * `ostia ci`'s policy for a workload with no matching baseline row (by
145
+ * workload id): `"fail"` exits 2 naming the baseline file, `"warn"` lists
146
+ * it in the report. Unset: `"fail"` when every workload is missing (a
147
+ * stale or wrong baseline), `"warn"` otherwise. */
148
+ onMissingBaseline?: "warn" | "fail";
149
+ /**
150
+ * Measure the machine's noise floor once per `ostia ci` run (default
151
+ * true) and stamp it on the candidate document, so `compare` widens its
152
+ * thresholds accordingly. `--no-noise-check` overrides this per run. */
153
+ noiseCheck?: boolean;
154
+ }
155
+
156
+ // Partial is shallow, so `thresholds` needs its own Partial to merge
157
+ // field-by-field.
158
+ export type OstiaConfigInput = Omit<Partial<OstiaConfig>, "thresholds"> & {
159
+ thresholds?: Partial<Thresholds>;
160
+ };
161
+
162
+ // Under node_modules/.cache because it's gitignored everywhere already.
163
+ export const DEFAULT_OUT_DIR = "node_modules/.cache/ostia";
164
+
165
+ // Baselines must survive node_modules churn, so they live outside outDir.
166
+ const DEFAULT_BASELINE_DIR = ".ostia/baselines";
167
+
168
+ export const DEFAULT_CONFIG: OstiaConfig = {
169
+ warmup: 3,
170
+ outDir: DEFAULT_OUT_DIR,
171
+ baselineDir: DEFAULT_BASELINE_DIR,
172
+ baseline: "main",
173
+ thresholds: DEFAULT_THRESHOLDS,
174
+ workloads: [],
175
+ };
176
+
177
+ // Renamed fields fail loudly instead of being silently ignored.
178
+ const RENAMED_FIELDS: Record<string, string> = { runs: "samples" };
179
+
180
+ // invariant: in discovery order, so `.ts` wins over JSON.
181
+ export const CONFIG_FILES: string[] = ["ostia.config.ts", "ostia.config.json"];
182
+
183
+ const warnConfig = (message: string) => console.warn(`ostia: ${message}`);
184
+
185
+ // An explicit `undefined` (`warmup: undefined`) means "unset", so it must
186
+ // not overwrite the default.
187
+ function withoutUndefined<T extends object>(obj: T): T {
188
+ const out = { ...obj };
189
+ for (const key in out) if (out[key] === undefined) delete out[key];
190
+ return out;
191
+ }
192
+
193
+ function isRecord(v: unknown): v is Record<string, unknown> {
194
+ return typeof v === "object" && v !== null && !Array.isArray(v);
195
+ }
196
+
197
+ // Sound because validateConfig checks every key OstiaConfigInput has; it
198
+ // only warns on the rest and leaves them in.
199
+ function assertConfigInput(
200
+ raw: Record<string, unknown>,
201
+ path: string,
202
+ ): asserts raw is Record<string, unknown> & OstiaConfigInput {
203
+ validateConfig(raw, path, warnConfig);
204
+ }
205
+
206
+ function resolveConfig(raw: unknown, path: string): OstiaConfig {
207
+ if (!isRecord(raw)) {
208
+ throw new ConfigError(`${path}: expected an object.`);
209
+ }
210
+ for (const [old, current] of Object.entries(RENAMED_FIELDS)) {
211
+ if (old in raw) {
212
+ throw new ConfigError(`${path}: "${old}" was renamed to "${current}".`);
213
+ }
214
+ }
215
+ assertConfigInput(raw, path);
216
+ const input = withoutUndefined(raw);
217
+ return {
218
+ ...DEFAULT_CONFIG,
219
+ ...input,
220
+ thresholds: {
221
+ ...DEFAULT_THRESHOLDS,
222
+ ...(input.thresholds && withoutUndefined(input.thresholds)),
223
+ },
224
+ };
225
+ }
226
+
227
+ async function readConfigFile(path: string): Promise<unknown> {
228
+ const absPath = path.startsWith("/") ? path : `${process.cwd()}/${path}`;
229
+ const file = Bun.file(absPath);
230
+ if (!(await file.exists())) return undefined;
231
+ try {
232
+ if (!path.endsWith(".ts")) return await file.json();
233
+ const mod: unknown = await import(absPath);
234
+ const exported =
235
+ typeof mod === "object" && mod !== null && "default" in mod
236
+ ? mod.default
237
+ : undefined;
238
+ if (exported === undefined) {
239
+ throw new Error(
240
+ `no default export; use "export default defineConfig({ ... })"`,
241
+ );
242
+ }
243
+ return exported;
244
+ } catch (err) {
245
+ throw new ConfigError(`${path}: ${errorMessage(err)}`);
246
+ }
247
+ }
248
+
249
+ async function existingConfigFiles(): Promise<string[]> {
250
+ const found: string[] = [];
251
+ for (const file of CONFIG_FILES) {
252
+ if (await Bun.file(file).exists()) found.push(file);
253
+ }
254
+ return found;
255
+ }
256
+
257
+ // `undefined` only when there is no such file; one that exists but is
258
+ // unusable throws `ConfigError` naming the bad key.
259
+ export async function loadConfig(
260
+ path?: string,
261
+ ): Promise<OstiaConfig | undefined> {
262
+ let file = path;
263
+ if (file === undefined) {
264
+ const found = await existingConfigFiles();
265
+ if (found.length > 1) {
266
+ warnConfig(
267
+ `${found.join(" and ")} both exist; using ${found[0]} and ignoring the rest.`,
268
+ );
269
+ }
270
+ file = found[0];
271
+ }
272
+ if (file === undefined) return undefined;
273
+ const raw = await readConfigFile(file);
274
+ return raw === undefined ? undefined : resolveConfig(raw, file);
275
+ }
276
+
277
+ export function baselinePath(config: OstiaConfig, name?: string): string {
278
+ return `${config.baselineDir}/${name ?? config.baseline}.json`;
279
+ }
280
+
281
+ export async function configFilePath(): Promise<string | undefined> {
282
+ return (await existingConfigFiles())[0];
283
+ }
@@ -0,0 +1,273 @@
1
+ import { errorMessage } from "../errors.ts";
2
+
3
+ /**
4
+ * A config file that exists but can't be used; the CLI reports it as
5
+ * `config-invalid`.
6
+ */
7
+ export class ConfigError extends Error {}
8
+
9
+ type Rule = (v: unknown) => boolean;
10
+ type Guard<T> = (v: unknown) => v is T;
11
+
12
+ const isObject = (v: unknown): v is Record<string, unknown> =>
13
+ typeof v === "object" && v !== null && !Array.isArray(v);
14
+
15
+ const isInt =
16
+ (min: number): Guard<number> =>
17
+ (v): v is number =>
18
+ typeof v === "number" && Number.isInteger(v) && v >= min;
19
+ const isNum =
20
+ (min: number): Guard<number> =>
21
+ (v): v is number =>
22
+ typeof v === "number" && Number.isFinite(v) && v >= min;
23
+ const isString: Guard<string> = (v) => typeof v === "string";
24
+ const isBool: Rule = (v) => typeof v === "boolean";
25
+ const isStringArray: Guard<string[]> = (v): v is string[] =>
26
+ Array.isArray(v) && v.every(isString);
27
+ const oneOf =
28
+ (...values: unknown[]): Rule =>
29
+ (v) =>
30
+ values.includes(v);
31
+
32
+ interface Field {
33
+ ok: Rule;
34
+ expects: string;
35
+ }
36
+
37
+ const field = (ok: Rule, expects: string): Field => ({ ok, expects });
38
+ const posInt = field(isInt(1), "a positive integer");
39
+ const nonNegInt = field(isInt(0), "a non-negative integer");
40
+ const text = field(isString, "a string");
41
+ const flag = field(isBool, "a boolean");
42
+ const strings = field(isStringArray, "an array of strings");
43
+
44
+ const THRESHOLD_FIELDS: Record<string, Field> = {
45
+ timingPct: field(isNum(0), "a non-negative number"),
46
+ frameSelfPct: field(isNum(0), "a non-negative number"),
47
+ heapTypePct: field(isNum(0), "a non-negative number"),
48
+ minFrameSelfUs: field(isNum(0), "a non-negative number"),
49
+ alpha: field((v) => isNum(0)(v) && v <= 1, "a number in [0, 1]"),
50
+ bootstrapIterations: posInt,
51
+ };
52
+
53
+ const PROJECT_FIELDS: Record<string, Field> = {
54
+ suites: field(
55
+ (v) => isStringArray(v) && v.length > 0,
56
+ "a non-empty array of glob strings",
57
+ ),
58
+ preload: strings,
59
+ bunFlags: strings,
60
+ };
61
+
62
+ const BENCH_FIELDS: Record<string, Field> = {
63
+ suites: strings,
64
+ projects: field(Array.isArray, "an array of project objects"),
65
+ preload: strings,
66
+ bunFlags: strings,
67
+ jobs: field(
68
+ (v) => isInt(1)(v) || v === "auto",
69
+ `a positive integer or "auto"`,
70
+ ),
71
+ budgetMs: field(isNum(0), "a non-negative number"),
72
+ samples: posInt,
73
+ minSamples: posInt,
74
+ gc: flag,
75
+ cpu: flag,
76
+ cpuIntervalUs: posInt,
77
+ alloc: flag,
78
+ peakMem: flag,
79
+ filter: text,
80
+ isolate: flag,
81
+ outDir: text,
82
+ timeoutMs: posInt,
83
+ };
84
+
85
+ const AB_FIELDS: Record<string, Field> = {
86
+ setup: field(
87
+ (v) => isString(v) || isStringArray(v),
88
+ "a command string or an array of them",
89
+ ),
90
+ keepTrees: posInt,
91
+ metric: field(oneOf("time", "instructions"), `"time" or "instructions"`),
92
+ alloc: flag,
93
+ peakMem: flag,
94
+ memThresholdPct: field(isNum(0), "a non-negative number"),
95
+ };
96
+
97
+ const COMMAND_ONLY = ["inputs", "prepare", "timeSource", "ignoreExitCodes"];
98
+
99
+ const WORKLOAD_FIELDS: Record<string, Field> = {
100
+ label: text,
101
+ command: field(
102
+ (v) => isStringArray(v) && v.length > 0,
103
+ "a non-empty array of strings (argv, no shell)",
104
+ ),
105
+ suites: field(
106
+ (v) => isStringArray(v) && v.length > 0,
107
+ "a non-empty array of glob strings",
108
+ ),
109
+ inputs: strings,
110
+ prepare: field(
111
+ (v) => isString(v) || isStringArray(v) || typeof v === "function",
112
+ "a command string, an argv array, or (ostia.config.ts) a function",
113
+ ),
114
+ timeSource: field(
115
+ (v) =>
116
+ isObject(v) &&
117
+ (isString(v.pattern) || v.pattern instanceof RegExp) &&
118
+ (v.group === undefined || isInt(0)(v.group)) &&
119
+ (v.unit === undefined || oneOf("ns", "us", "ms", "s")(v.unit)),
120
+ `an object { pattern, group?, unit? } with a regex source string (or RegExp) pattern, an integer group, and unit "ns" | "us" | "ms" | "s"`,
121
+ ),
122
+ timeoutMs: posInt,
123
+ ignoreExitCodes: field(
124
+ (v) => Array.isArray(v) && v.every((c) => isInt(0)(c) && c <= 255),
125
+ "an array of exit codes 0-255",
126
+ ),
127
+ };
128
+
129
+ const TOP_FIELDS: Record<string, Field> = {
130
+ samples: posInt,
131
+ budgetMs: field(isNum(0), "a non-negative number"),
132
+ minSamples: posInt,
133
+ warmup: nonNegInt,
134
+ outDir: field((v) => isString(v) && v !== "", "a non-empty string"),
135
+ baselineDir: field((v) => isString(v) && v !== "", "a non-empty string"),
136
+ baseline: field((v) => isString(v) && v !== "", "a non-empty string"),
137
+ onMissingBaseline: field(oneOf("warn", "fail"), `"warn" or "fail"`),
138
+ noiseCheck: flag,
139
+ };
140
+
141
+ const describe = (v: unknown): string =>
142
+ typeof v === "function"
143
+ ? "a function"
144
+ : v instanceof RegExp
145
+ ? String(v)
146
+ : (JSON.stringify(v) ?? String(v));
147
+
148
+ // Checks each present (non-`undefined`) key of `obj` against `fields`;
149
+ // unknown keys are reported to `warn` rather than failing, as they always
150
+ // were ignored. A `$`-prefixed key (`"$schema"`) is never reported.
151
+ function checkFields(
152
+ obj: Record<string, unknown>,
153
+ fields: Record<string, Field>,
154
+ where: string,
155
+ file: string,
156
+ warn: (message: string) => void,
157
+ ): void {
158
+ const prefix = where === "" ? "" : `${where}.`;
159
+ for (const [key, value] of Object.entries(obj)) {
160
+ if (value === undefined) continue;
161
+ const spec = Object.hasOwn(fields, key) ? fields[key] : undefined;
162
+ if (!spec) {
163
+ if (!key.startsWith("$")) {
164
+ warn(`${file}: unknown key "${prefix}${key}" is ignored.`);
165
+ }
166
+ } else if (!spec.ok(value)) {
167
+ throw new ConfigError(
168
+ `${file}: "${prefix}${key}" must be ${spec.expects}, got ${describe(value)}.`,
169
+ );
170
+ }
171
+ }
172
+ }
173
+
174
+ function checkObject(
175
+ value: unknown,
176
+ where: string,
177
+ file: string,
178
+ ): Record<string, unknown> {
179
+ if (!isObject(value)) {
180
+ throw new ConfigError(
181
+ `${file}: "${where}" must be an object, got ${describe(value)}.`,
182
+ );
183
+ }
184
+ return value;
185
+ }
186
+
187
+ function checkWorkload(
188
+ wc: unknown,
189
+ i: number,
190
+ file: string,
191
+ warn: (message: string) => void,
192
+ ): void {
193
+ const where = `workloads[${i}]`;
194
+ const obj = checkObject(wc, where, file);
195
+ const has = (key: string) => obj[key] !== undefined;
196
+ if (has("command") === has("suites")) {
197
+ throw new ConfigError(
198
+ `${file}: "${where}" needs exactly one of "command" or "suites".`,
199
+ );
200
+ }
201
+ checkFields(obj, WORKLOAD_FIELDS, where, file, warn);
202
+ if (has("suites")) {
203
+ for (const key of COMMAND_ONLY) {
204
+ if (has(key)) {
205
+ warn(
206
+ `${file}: "${where}.${key}" applies to command workloads only; ignored on a suites workload.`,
207
+ );
208
+ }
209
+ }
210
+ }
211
+ const source = isObject(obj.timeSource) ? obj.timeSource.pattern : undefined;
212
+ if (typeof source === "string") {
213
+ try {
214
+ new RegExp(source);
215
+ } catch (err) {
216
+ throw new ConfigError(
217
+ `${file}: "${where}.timeSource.pattern" is not a valid regex: ${errorMessage(err)}`,
218
+ );
219
+ }
220
+ }
221
+ }
222
+
223
+ // Throws `ConfigError` naming the offending key for a wrong type or value;
224
+ // `warn` gets keys that are unknown (or inapplicable) and so ignored.
225
+ // `raw` is the already-object-checked config with `undefined` values still
226
+ // present.
227
+ export function validateConfig(
228
+ raw: Record<string, unknown>,
229
+ file: string,
230
+ warn: (message: string) => void,
231
+ ): void {
232
+ const { thresholds, workloads, bench, ab, ...rest } = raw;
233
+ checkFields(rest, TOP_FIELDS, "", file, warn);
234
+ if (thresholds !== undefined) {
235
+ checkFields(
236
+ checkObject(thresholds, "thresholds", file),
237
+ THRESHOLD_FIELDS,
238
+ "thresholds",
239
+ file,
240
+ warn,
241
+ );
242
+ }
243
+ if (bench !== undefined) {
244
+ const benchObj = checkObject(bench, "bench", file);
245
+ checkFields(benchObj, BENCH_FIELDS, "bench", file, warn);
246
+ // invariant: checkFields has made `projects` an array when present.
247
+ const projects: unknown = benchObj.projects;
248
+ for (const [i, project] of (Array.isArray(projects)
249
+ ? projects
250
+ : []
251
+ ).entries()) {
252
+ const where = `bench.projects[${i}]`;
253
+ const obj = checkObject(project, where, file);
254
+ if (obj.suites === undefined) {
255
+ throw new ConfigError(`${file}: "${where}" needs "suites".`);
256
+ }
257
+ checkFields(obj, PROJECT_FIELDS, where, file, warn);
258
+ }
259
+ }
260
+ if (ab !== undefined) {
261
+ checkFields(checkObject(ab, "ab", file), AB_FIELDS, "ab", file, warn);
262
+ }
263
+ if (workloads !== undefined) {
264
+ if (!Array.isArray(workloads)) {
265
+ throw new ConfigError(
266
+ `${file}: "workloads" must be an array, got ${describe(workloads)}.`,
267
+ );
268
+ }
269
+ for (const [i, wc] of workloads.entries()) {
270
+ checkWorkload(wc, i, file, warn);
271
+ }
272
+ }
273
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,8 @@
1
+ export function errorMessage(err: unknown): string {
2
+ return err instanceof Error ? err.message : String(err);
3
+ }
4
+
5
+ /** The caller's input can't be run as given (missing suite, bad ref, absent
6
+ * baseline): the CLI reports it as a usage error (exit 2) rather than an
7
+ * internal failure. */
8
+ export class OstiaUsageError extends Error {}
package/src/format.ts ADDED
@@ -0,0 +1,35 @@
1
+ // Duration formatting shared by the stats warnings and every renderer; a
2
+ // leaf module so neither imports the other.
3
+
4
+ export type DurationUnit = "ns" | "µs" | "ms" | "s";
5
+
6
+ const UNIT_DIVISORS: Record<DurationUnit, number> = {
7
+ ns: 1,
8
+ µs: 1e3,
9
+ ms: 1e6,
10
+ s: 1e9,
11
+ };
12
+
13
+ export function pickDurationUnit(ns: number): DurationUnit {
14
+ const abs = Math.abs(ns);
15
+ if (abs >= 1e9) return "s";
16
+ if (abs >= 1e6) return "ms";
17
+ if (abs >= 1e3) return "µs";
18
+ return "ns";
19
+ }
20
+
21
+ // 2 decimals under 10, else 1: never fewer than one.
22
+ function sigFigDecimals(value: number): number {
23
+ const intDigits = Math.floor(Math.log10(Math.max(Math.abs(value), 1))) + 1;
24
+ return Math.max(1, 3 - intDigits);
25
+ }
26
+
27
+ // Pass `unit` so a row's columns share one unit instead of each picking
28
+ // its own.
29
+ export function formatDuration(
30
+ ns: number,
31
+ unit: DurationUnit = pickDurationUnit(ns),
32
+ ): string {
33
+ const value = ns / UNIT_DIVISORS[unit];
34
+ return `${value.toFixed(sigFigDecimals(value))} ${unit}`;
35
+ }
package/src/glob.ts ADDED
@@ -0,0 +1,45 @@
1
+ import { resolve } from "node:path";
2
+
3
+ const SKIPPED_DIRS = ["node_modules", ".git"];
4
+ // Wildcards skip it because `ostia ab` extracts copies of the project
5
+ // there.
6
+ const AB_TREES = ".ostia/ab";
7
+ // compat: `@(` and `+(` open extglobs since Bun 1.4.4; a bare `(` isn't a
8
+ // glob character, so `app/(marketing)` stays literal.
9
+ const GLOB_CHARS = /[*?[\]{}!]|[@+]\(/;
10
+
11
+ // Only the segments past the pattern's literal prefix were chosen by a
12
+ // wildcard, so only those can wander into a skipped directory.
13
+ function wildcardSegments(pattern: string, path: string): [string[], string[]] {
14
+ const patternSegs = pattern.split("/");
15
+ const literal = patternSegs.findIndex((s) => GLOB_CHARS.test(s));
16
+ const from = literal < 0 ? patternSegs.length : literal;
17
+ return [patternSegs.slice(from), path.split("/").slice(from)];
18
+ }
19
+
20
+ // Relative to `cwd`, deduped and sorted. Dotfiles match (`.github/**`),
21
+ // but wildcards never descend into `node_modules`, `.git` or `.ostia/ab`
22
+ // unless the pattern names that directory itself.
23
+ export async function scanGlobs(
24
+ patterns: string[],
25
+ cwd: string,
26
+ ): Promise<string[]> {
27
+ const paths = new Set<string>();
28
+ for (const pattern of patterns) {
29
+ // Bun.Glob matches nothing for an absolute path with no wildcard.
30
+ if (!GLOB_CHARS.test(pattern)) {
31
+ if (await Bun.file(resolve(cwd, pattern)).exists()) paths.add(pattern);
32
+ continue;
33
+ }
34
+ for await (const path of new Bun.Glob(pattern).scan({ cwd, dot: true })) {
35
+ const [named, matched] = wildcardSegments(pattern, path);
36
+ const skipped = matched.some(
37
+ (seg) => SKIPPED_DIRS.includes(seg) && !named.includes(seg),
38
+ );
39
+ const inTrees =
40
+ `/${path}/`.includes(`/${AB_TREES}/`) && !pattern.includes(AB_TREES);
41
+ if (!skipped && !inTrees) paths.add(path);
42
+ }
43
+ }
44
+ return [...paths].sort();
45
+ }