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,440 @@
1
+ import { bench, resolveBenchOptions } from "../bench/index.ts";
2
+ import { captureRunEnvironment } from "../bench/support.ts";
3
+ import { computeCacheKey, computeInputsDigest } from "../cache/fingerprint.ts";
4
+ import { readCachedRun, writeCachedRun } from "../cache/store.ts";
5
+ import { createComparer, summarizeComparisons } from "../compare/index.ts";
6
+ import {
7
+ baselinePath,
8
+ type OstiaConfig,
9
+ type WorkloadConfig,
10
+ } from "../config/index.ts";
11
+ import { OstiaUsageError } from "../errors.ts";
12
+ import { scanGlobs } from "../glob.ts";
13
+ import {
14
+ configFingerprint,
15
+ createDocument,
16
+ loadDocument,
17
+ makeSubprocessWorkload,
18
+ makeTimingMeasurement,
19
+ } from "../ir/document.ts";
20
+ import type {
21
+ Comparison,
22
+ Environment,
23
+ Measurement,
24
+ ProfileDocument,
25
+ Warning,
26
+ Workload,
27
+ } from "../ir/types.ts";
28
+ import { stampDrift } from "../measure/environment.ts";
29
+ import { isHarnessFailure, runTimingPhase } from "../measure/timing.ts";
30
+ import { formatSignedPct, workloadLabel } from "../renderers/format.ts";
31
+ import { abortedWarning } from "../time.ts";
32
+ import { TOOL_VERSION } from "../version.ts";
33
+
34
+ interface CiOptions {
35
+ config: OstiaConfig;
36
+ full: boolean;
37
+ baselineName?: string;
38
+ /**
39
+ * Abort kills in-flight trials and suite processes and stops scheduling
40
+ * workloads. `runCi` then resolves with `aborted: true`: the document
41
+ * holds what completed, nothing is compared, and no run is written to the
42
+ * cache. */
43
+ signal?: AbortSignal;
44
+ }
45
+
46
+ // So a hung workload times out instead of blocking a CI job;
47
+ // `WorkloadConfig.timeoutMs` / `BenchConfig.timeoutMs` override this.
48
+ const DEFAULT_CI_TIMEOUT_MS = 600_000;
49
+
50
+ type WorkloadStatus = "cached" | "executed";
51
+
52
+ interface MeasuredWorkload {
53
+ workload: Workload;
54
+ status: WorkloadStatus;
55
+ run: Measurement;
56
+ /**
57
+ * `command` workloads only (see `isHarnessFailure`): not a regression, so
58
+ * gated separately from a timing verdict. Always `false` for `suites`. */
59
+ harnessFailed: boolean;
60
+ }
61
+
62
+ interface CiWorkloadResult extends MeasuredWorkload {
63
+ comparison?: Comparison;
64
+ }
65
+
66
+ interface CiSummary {
67
+ total: number;
68
+ cached: number;
69
+ executed: number;
70
+ passed: number;
71
+ regressed: number;
72
+ missingBaseline: number;
73
+ /**
74
+ * Count of `results` with `harnessFailed: true`; always gates the exit to
75
+ * 2.
76
+ */
77
+ failed: number;
78
+ results: CiWorkloadResult[];
79
+ /**
80
+ * Workloads on only one side: `candOnly` is what `missingBaseline` counts,
81
+ * as full `Workload`s so a renderer can name them. */
82
+ unmatched: { baseOnly: Workload[]; candOnly: Workload[] };
83
+ }
84
+
85
+ /**
86
+ * Base of the two baseline errors, so the CLI reports either as
87
+ * `baseline-missing`.
88
+ */
89
+ export class BaselineError extends OstiaUsageError {}
90
+
91
+ export class BaselineNotFoundError extends BaselineError {
92
+ readonly path: string;
93
+
94
+ constructor(path: string) {
95
+ super(
96
+ `No baseline document at ${path}. Create one with: ostia baseline save ${path
97
+ .slice(path.lastIndexOf("/") + 1)
98
+ .replace(/\.json$/, "")}`,
99
+ );
100
+ this.path = path;
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Thrown by `runCi` when the `onMissingBaseline` policy makes unmatched
106
+ * workloads a hard error. */
107
+ export class MissingBaselineError extends BaselineError {
108
+ readonly path: string;
109
+ readonly missing: number;
110
+ readonly total: number;
111
+
112
+ constructor(path: string, missing: number, total: number) {
113
+ super(
114
+ `${missing} of ${total} configured workload(s) have no matching row in baseline ${path} (by workload id). Re-seed with: ostia baseline save`,
115
+ );
116
+ this.path = path;
117
+ this.missing = missing;
118
+ this.total = total;
119
+ }
120
+ }
121
+
122
+ interface MeasureConfigWorkloadsResult {
123
+ results: MeasuredWorkload[];
124
+ /**
125
+ * One reference measurement taken before any workload runs, unless
126
+ * `config.noiseCheck` is false. */
127
+ environment?: Environment | undefined;
128
+ /** The signal fired: `results` holds only what completed. */
129
+ aborted: boolean;
130
+ }
131
+
132
+ async function measureSuiteWorkloads(
133
+ config: OstiaConfig,
134
+ wc: WorkloadConfig,
135
+ suites: string[],
136
+ noiseWarning: Warning | undefined,
137
+ signal: AbortSignal | undefined,
138
+ ): Promise<MeasuredWorkload[]> {
139
+ // Always executes: a suite file's task ids (so its cache keys) are unknown
140
+ // without importing it.
141
+ const suiteFiles = await scanGlobs(suites, process.cwd());
142
+ if (suiteFiles.length === 0) {
143
+ // Gating zero tasks would pass silently.
144
+ throw new OstiaUsageError(
145
+ `Workload suites ${JSON.stringify(suites)} matched no files.`,
146
+ );
147
+ }
148
+ // Same CLI-over-config resolution as `ostia bench`; only the defaults
149
+ // differ.
150
+ const benchOpts = await resolveBenchOptions(
151
+ { suites: suiteFiles, preload: [], bunFlags: [], noiseCheck: false },
152
+ config.bench,
153
+ );
154
+ const doc = await bench({
155
+ ...benchOpts,
156
+ outDir: benchOpts.outDir ?? config.outDir,
157
+ timeoutMs: wc.timeoutMs ?? benchOpts.timeoutMs ?? DEFAULT_CI_TIMEOUT_MS,
158
+ ...(signal && { signal }),
159
+ });
160
+ const results: MeasuredWorkload[] = [];
161
+ for (const workload of doc.workloads) {
162
+ const run = doc.measurements.find(
163
+ (m) => m.workloadId === workload.id && m.phase === "timing",
164
+ );
165
+ // A task.skip()'d task has no timing measurement: nothing to gate.
166
+ if (!run) continue;
167
+ if (noiseWarning) run.warnings.push(noiseWarning);
168
+ results.push({ workload, status: "executed", run, harnessFailed: false });
169
+ }
170
+ return results;
171
+ }
172
+
173
+ async function measureCommandWorkload(
174
+ config: OstiaConfig,
175
+ wc: WorkloadConfig,
176
+ command: string[],
177
+ full: boolean,
178
+ noiseWarning: Warning | undefined,
179
+ signal: AbortSignal | undefined,
180
+ ): Promise<MeasuredWorkload> {
181
+ const workload = makeSubprocessWorkload(command, wc.label, {
182
+ ...(wc.prepare !== undefined && { prepare: wc.prepare }),
183
+ ...(wc.timeSource !== undefined && { timeSource: wc.timeSource }),
184
+ });
185
+ const cfgFp = configFingerprint({
186
+ samples: config.samples ?? null,
187
+ budgetMs: config.budgetMs ?? null,
188
+ minSamples: config.minSamples ?? null,
189
+ warmup: config.warmup,
190
+ });
191
+ // Only declared `inputs` say what a cached run depends on (`inputs: []`
192
+ // means "nothing"). A function-form prepare can read anything, so it never
193
+ // comes from cache either.
194
+ const cacheable = wc.inputs !== undefined && typeof wc.prepare !== "function";
195
+ const cacheKey = computeCacheKey({
196
+ workloadId: workload.id,
197
+ phase: "timing",
198
+ configFingerprint: cfgFp,
199
+ bunVersion: Bun.version,
200
+ toolVersion: TOOL_VERSION,
201
+ instrumented: false,
202
+ inputsDigest: await computeInputsDigest(wc.inputs ?? []),
203
+ });
204
+
205
+ const cachedRun =
206
+ full || !cacheable
207
+ ? undefined
208
+ : await readCachedRun(config.outDir, cacheKey);
209
+ let run: Measurement;
210
+ if (cachedRun) {
211
+ run = cachedRun;
212
+ } else {
213
+ const phaseResult = await runTimingPhase({
214
+ argv: command,
215
+ ...(config.samples !== undefined && { samples: config.samples }),
216
+ ...(config.budgetMs !== undefined && { budgetMs: config.budgetMs }),
217
+ ...(config.minSamples !== undefined && {
218
+ minSamples: config.minSamples,
219
+ }),
220
+ ...(config.warmup !== undefined && { warmup: config.warmup }),
221
+ ...(wc.prepare !== undefined && { prepare: wc.prepare }),
222
+ ...(wc.timeSource !== undefined && { timeSource: wc.timeSource }),
223
+ timeoutMs: wc.timeoutMs ?? DEFAULT_CI_TIMEOUT_MS,
224
+ ...(wc.ignoreExitCodes !== undefined && {
225
+ ignoreExitCodes: wc.ignoreExitCodes,
226
+ }),
227
+ ...(signal && { signal }),
228
+ });
229
+ run = makeTimingMeasurement({
230
+ workload,
231
+ configFingerprint: cfgFp,
232
+ trials: phaseResult.trials,
233
+ ...(phaseResult.timing && { timing: phaseResult.timing }),
234
+ warnings: noiseWarning
235
+ ? [...phaseResult.warnings, noiseWarning]
236
+ : phaseResult.warnings,
237
+ });
238
+ // A cancelled run holds partial trials, which must never be served later.
239
+ if (cacheable && !signal?.aborted) {
240
+ await writeCachedRun(config.outDir, cacheKey, run);
241
+ }
242
+ }
243
+
244
+ return {
245
+ workload,
246
+ status: cachedRun ? "cached" : "executed",
247
+ run,
248
+ harnessFailed: isHarnessFailure(run, wc.ignoreExitCodes),
249
+ };
250
+ }
251
+
252
+ // No baseline comparison. Shared by `runCi` and `ostia baseline save`, so
253
+ // a saved baseline comes from the same code path `ci` gates against.
254
+ export async function measureConfigWorkloads(
255
+ config: OstiaConfig,
256
+ full: boolean,
257
+ signal?: AbortSignal,
258
+ ): Promise<MeasureConfigWorkloadsResult> {
259
+ // Stamped on every measurement taken now, never on a cached one.
260
+ const { environment, noiseWarning } = captureRunEnvironment(
261
+ config.noiseCheck,
262
+ );
263
+ const results: MeasuredWorkload[] = [];
264
+ for (const wc of config.workloads) {
265
+ if (signal?.aborted) break;
266
+ if (wc.suites) {
267
+ results.push(
268
+ ...(await measureSuiteWorkloads(
269
+ config,
270
+ wc,
271
+ wc.suites,
272
+ noiseWarning,
273
+ signal,
274
+ )),
275
+ );
276
+ } else if (wc.command) {
277
+ results.push(
278
+ await measureCommandWorkload(
279
+ config,
280
+ wc,
281
+ wc.command,
282
+ full,
283
+ noiseWarning,
284
+ signal,
285
+ ),
286
+ );
287
+ } else {
288
+ // invariant: config validation gives every workload exactly one of
289
+ // `command` and `suites`.
290
+ throw new Error("ci: a workload has neither command nor suites");
291
+ }
292
+ }
293
+ const aborted = signal?.aborted ?? false;
294
+ const last = results.at(-1)?.run;
295
+ if (aborted && last && !last.warnings.some((w) => w.code === "aborted")) {
296
+ last.warnings = [...last.warnings, abortedWarning()];
297
+ }
298
+ if (results.some((r) => r.status === "executed")) stampDrift(environment);
299
+ return { results, environment, aborted };
300
+ }
301
+
302
+ export async function runCi(opts: CiOptions): Promise<{
303
+ document: ProfileDocument;
304
+ summary: CiSummary;
305
+ /**
306
+ * The baseline `document` was compared against, so a caller can report its
307
+ * `git` without loading it again. */
308
+ baseline: ProfileDocument;
309
+ /** Cancelled by `signal`: `document` is partial and has no comparisons. */
310
+ aborted: boolean;
311
+ }> {
312
+ const { config } = opts;
313
+ const path = baselinePath(config, opts.baselineName);
314
+ if (!(await Bun.file(path).exists())) {
315
+ throw new BaselineNotFoundError(path);
316
+ }
317
+ const baseline = await loadDocument(path);
318
+
319
+ const {
320
+ results: measured,
321
+ environment,
322
+ aborted,
323
+ } = await measureConfigWorkloads(config, opts.full, opts.signal);
324
+ const results: CiWorkloadResult[] = measured.map((m) => ({ ...m }));
325
+ const executed = results.filter((r) => r.status === "executed").length;
326
+ const candidateDoc = createDocument(
327
+ results.map((r) => r.workload),
328
+ results.map((r) => r.run),
329
+ environment,
330
+ );
331
+
332
+ if (aborted) {
333
+ return {
334
+ document: candidateDoc,
335
+ summary: {
336
+ total: results.length,
337
+ cached: results.length - executed,
338
+ executed,
339
+ passed: 0,
340
+ regressed: 0,
341
+ missingBaseline: 0,
342
+ failed: 0,
343
+ results,
344
+ unmatched: { baseOnly: [], candOnly: [] },
345
+ },
346
+ baseline,
347
+ aborted,
348
+ };
349
+ }
350
+
351
+ const comparer = createComparer(baseline, candidateDoc, config.thresholds);
352
+ const matched: [string, Comparison][] = [];
353
+ for (const result of results) {
354
+ const comparison = comparer.compare(result.workload.id);
355
+ if (comparison) {
356
+ result.comparison = comparison;
357
+ matched.push([result.workload.id, comparison]);
358
+ }
359
+ }
360
+ const comparisons = matched.map(([, c]) => c);
361
+ const missingBaseline = results.length - comparisons.length;
362
+ const passed = comparisons.filter((c) => c.verdict === "pass").length;
363
+
364
+ // Unset: fail only when every workload is missing (a stale baseline file),
365
+ // warn when just some are (a workload added since the baseline was saved).
366
+ const policy =
367
+ config.onMissingBaseline ??
368
+ (missingBaseline === results.length ? "fail" : "warn");
369
+ if (missingBaseline > 0 && policy === "fail") {
370
+ throw new MissingBaselineError(path, missingBaseline, results.length);
371
+ }
372
+
373
+ const unmatched = comparer.unmatched();
374
+ candidateDoc.comparisons = comparisons;
375
+ candidateDoc.unmatched = {
376
+ baseOnly: unmatched.baseOnly.map((w) => w.id),
377
+ candOnly: unmatched.candOnly.map((w) => w.id),
378
+ };
379
+ candidateDoc.compared = comparer.compared(matched);
380
+ candidateDoc.comparisonSummary = summarizeComparisons(
381
+ comparisons,
382
+ comparer.effectiveTimingPct,
383
+ comparer.driftPct,
384
+ );
385
+
386
+ return {
387
+ document: candidateDoc,
388
+ summary: {
389
+ total: results.length,
390
+ cached: results.length - executed,
391
+ executed,
392
+ passed,
393
+ regressed: comparisons.length - passed,
394
+ missingBaseline,
395
+ failed: results.filter((r) => r.harnessFailed).length,
396
+ results,
397
+ unmatched,
398
+ },
399
+ baseline,
400
+ aborted: false,
401
+ };
402
+ }
403
+
404
+ export function renderCiReport(summary: CiSummary): string {
405
+ const lines = [
406
+ `${summary.total} workloads`,
407
+ `${summary.cached} cached`,
408
+ `${summary.executed} executed`,
409
+ ];
410
+ if (summary.missingBaseline > 0) {
411
+ lines.push(
412
+ `${summary.missingBaseline} skipped (no matching baseline workload)`,
413
+ );
414
+ }
415
+ if (summary.failed > 0) {
416
+ const failedLabels = summary.results
417
+ .filter((r) => r.harnessFailed)
418
+ .map((r) => workloadLabel(r.workload));
419
+ lines.push(
420
+ `${summary.failed} failed (harness error, a command exited non-zero or produced no samples: ${failedLabels.join(", ")})`,
421
+ );
422
+ }
423
+
424
+ const regressionDetails = summary.results
425
+ .filter((r) => r.comparison?.verdict === "fail")
426
+ .map((r) => {
427
+ const t = r.comparison?.timing;
428
+ const label = workloadLabel(r.workload);
429
+ return t
430
+ ? `${formatSignedPct(t.medianDeltaPct)} median on ${label}`
431
+ : label;
432
+ });
433
+
434
+ lines.push(
435
+ `${summary.passed} passed ${summary.regressed} regressed${regressionDetails.length > 0 ? ` (${regressionDetails.join(", ")})` : ""}`,
436
+ "",
437
+ `Profile CI: ${summary.regressed > 0 || summary.failed > 0 ? "✗" : "✓"}`,
438
+ );
439
+ return `${lines.join("\n")}\n`;
440
+ }
@@ -0,0 +1,263 @@
1
+ import { availableJobs } from "../bench/index.ts";
2
+ import type { FormatName } from "../renderers/index.ts";
3
+ import { splitCommand } from "../spawn/index.ts";
4
+
5
+ /**
6
+ * Thrown for a malformed flag; the dispatcher prints it with a `--help`
7
+ * pointer and exits 2.
8
+ */
9
+ export class CliUsageError extends Error {}
10
+
11
+ const DOCUMENT_FORMATS = [
12
+ "table",
13
+ "json",
14
+ "jsonl",
15
+ "markdown",
16
+ "minimal",
17
+ ] as const;
18
+
19
+ export const VIZ_FORMATS = [
20
+ "collapsed",
21
+ "mermaid",
22
+ "speedscope",
23
+ "cpuprofile",
24
+ ] as const;
25
+
26
+ export const REPORT_FORMATS: readonly [
27
+ ...typeof DOCUMENT_FORMATS,
28
+ ...typeof VIZ_FORMATS,
29
+ ] = [...DOCUMENT_FORMATS, ...VIZ_FORMATS] as const;
30
+
31
+ export function parseIntFlag(
32
+ name: string,
33
+ raw: string | undefined,
34
+ opts: { min?: number; allowAuto?: boolean } = {},
35
+ ): number {
36
+ if (opts.allowAuto && raw === "auto") return availableJobs();
37
+ const min = opts.min ?? 1;
38
+ const n = raw?.trim() === "" ? Number.NaN : Number(raw);
39
+ if (!Number.isInteger(n) || n < min) {
40
+ throw new CliUsageError(
41
+ `Invalid ${name} "${raw}": expected an integer ≥ ${min}${
42
+ opts.allowAuto ? ` (or "auto")` : ""
43
+ }`,
44
+ );
45
+ }
46
+ return n;
47
+ }
48
+
49
+ function parseExitCodes(name: string, raw: string): number[] {
50
+ return raw.split(",").map((part) => {
51
+ const code = /^\d+$/.test(part) ? Number(part) : Number.NaN;
52
+ if (!(code <= 255)) {
53
+ throw new CliUsageError(
54
+ `Invalid ${name} "${raw}": expected exit codes 0-255, comma-separated`,
55
+ );
56
+ }
57
+ return code;
58
+ });
59
+ }
60
+
61
+ type FlagSpec =
62
+ | { kind: "string" }
63
+ | { kind: "int"; min?: number; allowAuto?: boolean }
64
+ | { kind: "number"; min: number }
65
+ | { kind: "bool"; value: boolean }
66
+ | { kind: "enum"; values: readonly string[] }
67
+ | { kind: "list" }
68
+ | { kind: "words" }
69
+ | { kind: "exitCodes" };
70
+
71
+ interface FlagDef {
72
+ dest: string;
73
+ spec: FlagSpec;
74
+ }
75
+
76
+ type FlagTable = Record<string, FlagDef>;
77
+
78
+ const def = (dest: string, spec: FlagSpec): FlagDef => ({ dest, spec });
79
+
80
+ export const flag = {
81
+ str: (dest: string): FlagDef => def(dest, { kind: "string" }),
82
+ int: (dest: string, min: number = 1, allowAuto: boolean = false): FlagDef =>
83
+ def(dest, { kind: "int", min, allowAuto }),
84
+ num: (dest: string, min: number): FlagDef =>
85
+ def(dest, { kind: "number", min }),
86
+ on: (dest: string): FlagDef => def(dest, { kind: "bool", value: true }),
87
+ off: (dest: string): FlagDef => def(dest, { kind: "bool", value: false }),
88
+ oneOf: (dest: string, values: readonly string[]): FlagDef =>
89
+ def(dest, { kind: "enum", values }),
90
+ /** Repeatable; each occurrence appends one value. */
91
+ list: (dest: string): FlagDef => def(dest, { kind: "list" }),
92
+ /** Repeatable; each occurrence is whitespace-split and appended. */
93
+ words: (dest: string): FlagDef => def(dest, { kind: "words" }),
94
+ /** `--flag[=CODE,...]`: bare means every non-zero exit code. */
95
+ exitCodes: (dest: string): FlagDef => def(dest, { kind: "exitCodes" }),
96
+ };
97
+
98
+ export interface OutputArgs {
99
+ exportJson?: string;
100
+ format: FormatName;
101
+ quiet: boolean;
102
+ help: boolean;
103
+ }
104
+
105
+ export interface RunArgs extends OutputArgs {
106
+ noiseCheck: boolean;
107
+ }
108
+
109
+ export const OUTPUT_DEFAULTS = {
110
+ format: "table",
111
+ quiet: false,
112
+ help: false,
113
+ } as const;
114
+
115
+ export const RUN_DEFAULTS: typeof OUTPUT_DEFAULTS & {
116
+ readonly noiseCheck: true;
117
+ } = { ...OUTPUT_DEFAULTS, noiseCheck: true } as const;
118
+
119
+ export const HELP_FLAGS: FlagTable = {
120
+ "--help": flag.on("help"),
121
+ "-h": flag.on("help"),
122
+ };
123
+
124
+ export const OUTPUT_FLAGS: FlagTable = {
125
+ ...HELP_FLAGS,
126
+ "--export-json": flag.str("exportJson"),
127
+ "--format": flag.oneOf("format", DOCUMENT_FORMATS),
128
+ "--quiet": flag.on("quiet"),
129
+ };
130
+
131
+ export const NOISE_CHECK_FLAGS: FlagTable = {
132
+ "--no-noise-check": flag.off("noiseCheck"),
133
+ };
134
+
135
+ export const CONFIG_FLAGS: FlagTable = {
136
+ "--config": flag.str("config"),
137
+ };
138
+
139
+ export interface ConfigArgs {
140
+ config?: string;
141
+ }
142
+
143
+ // Every command that runs measurements takes these, except `ci`, which
144
+ // doesn't take per-run flags.
145
+ export const RUN_FLAGS: FlagTable = {
146
+ ...OUTPUT_FLAGS,
147
+ ...NOISE_CHECK_FLAGS,
148
+ "--timeout": flag.int("timeoutMs"),
149
+ "--out-dir": flag.str("outDir"),
150
+ };
151
+
152
+ export const SUITE_FLAGS: FlagTable = {
153
+ ...RUN_FLAGS,
154
+ ...CONFIG_FLAGS,
155
+ "--filter": flag.str("filter"),
156
+ "--preload": flag.list("preload"),
157
+ "--bun-flags": flag.words("bunFlags"),
158
+ };
159
+
160
+ // invariant: a repeatable flag's `dest` starts as an array in the
161
+ // command's defaults.
162
+ function listAt(args: object, dest: string): unknown[] {
163
+ const list: unknown = Reflect.get(args, dest);
164
+ if (!Array.isArray(list)) {
165
+ throw new TypeError(`ostia: flag destination "${dest}" isn't an array`);
166
+ }
167
+ return list;
168
+ }
169
+
170
+ interface ParseSpec<T> {
171
+ command: string;
172
+ flags: FlagTable;
173
+ args: T;
174
+ /** Receives each bare word; omitted, a bare word is an unknown-flag error. */
175
+ positional?: (arg: string, args: T) => void;
176
+ /**
177
+ * Receives everything after a `--`, verbatim; omitted, `--` is an unknown
178
+ * flag.
179
+ */
180
+ rest?: (rest: string[], args: T) => void;
181
+ }
182
+
183
+ // Throws only `CliUsageError`, so the dispatcher can print a `--help`
184
+ // pointer for any parse failure. `--flag=value` equals `--flag value`.
185
+ export function parseFlags<T extends object>(
186
+ argv: string[],
187
+ { command, flags, args, positional, rest }: ParseSpec<T>,
188
+ ): T {
189
+ const set = (dest: string, value: unknown) => Reflect.set(args, dest, value);
190
+ for (let i = 0; i < argv.length; i++) {
191
+ const arg = argv[i] ?? "";
192
+ if (arg === "--" && rest) {
193
+ rest(argv.slice(i + 1), args);
194
+ break;
195
+ }
196
+ const eq = arg.startsWith("--") ? arg.indexOf("=") : -1;
197
+ const name = eq > 0 ? arg.slice(0, eq) : arg;
198
+ const flagDef = Object.hasOwn(flags, name) ? flags[name] : undefined;
199
+ if (!flagDef || (eq > 0 && flagDef.spec.kind === "bool")) {
200
+ if (arg.startsWith("-") || !positional) {
201
+ throw new CliUsageError(
202
+ `Unknown flag "${arg}" for "ostia ${command}".`,
203
+ );
204
+ }
205
+ positional(arg, args);
206
+ continue;
207
+ }
208
+ const value = (): string => {
209
+ if (eq > 0) return arg.slice(eq + 1);
210
+ if (i + 1 >= argv.length) {
211
+ throw new CliUsageError(`Missing value for ${name}.`);
212
+ }
213
+ return argv[++i] ?? "";
214
+ };
215
+ const { dest, spec } = flagDef;
216
+ switch (spec.kind) {
217
+ case "string":
218
+ set(dest, value());
219
+ break;
220
+ case "int":
221
+ set(dest, parseIntFlag(name, value(), spec));
222
+ break;
223
+ case "number": {
224
+ const raw = value();
225
+ const n = Number(raw);
226
+ if (raw === "" || !Number.isFinite(n) || n < spec.min) {
227
+ throw new CliUsageError(
228
+ `Invalid ${name} "${raw}": expected a number ≥ ${spec.min}`,
229
+ );
230
+ }
231
+ set(dest, n);
232
+ break;
233
+ }
234
+ case "bool":
235
+ set(dest, spec.value);
236
+ break;
237
+ case "list":
238
+ listAt(args, dest).push(value());
239
+ break;
240
+ case "words":
241
+ listAt(args, dest).push(...splitCommand(value()));
242
+ break;
243
+ case "exitCodes":
244
+ listAt(args, dest).push(
245
+ ...(eq > 0
246
+ ? parseExitCodes(name, arg.slice(eq + 1))
247
+ : Array.from({ length: 255 }, (_, n) => n + 1)),
248
+ );
249
+ break;
250
+ case "enum": {
251
+ const raw = value();
252
+ if (!spec.values.includes(raw)) {
253
+ throw new CliUsageError(
254
+ `Invalid ${name} "${raw}": expected one of: ${spec.values.join(", ")}`,
255
+ );
256
+ }
257
+ set(dest, raw);
258
+ break;
259
+ }
260
+ }
261
+ }
262
+ return args;
263
+ }