@ark/attest 0.9.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/LICENSE +7 -0
- package/README.md +284 -0
- package/out/assert/assertions.d.ts +28 -0
- package/out/assert/assertions.js +119 -0
- package/out/assert/attest.d.ts +26 -0
- package/out/assert/attest.js +40 -0
- package/out/assert/chainableAssertions.d.ts +68 -0
- package/out/assert/chainableAssertions.js +176 -0
- package/out/bench/await1k.d.ts +1 -0
- package/out/bench/await1k.js +1002 -0
- package/out/bench/baseline.d.ts +5 -0
- package/out/bench/baseline.js +60 -0
- package/out/bench/bench.d.ts +58 -0
- package/out/bench/bench.js +216 -0
- package/out/bench/call1k.d.ts +1 -0
- package/out/bench/call1k.js +1002 -0
- package/out/bench/measure.d.ts +29 -0
- package/out/bench/measure.js +48 -0
- package/out/bench/type.d.ts +16 -0
- package/out/bench/type.js +36 -0
- package/out/cache/getCachedAssertions.d.ts +11 -0
- package/out/cache/getCachedAssertions.js +70 -0
- package/out/cache/snapshots.d.ts +29 -0
- package/out/cache/snapshots.js +153 -0
- package/out/cache/ts.d.ts +45 -0
- package/out/cache/ts.js +127 -0
- package/out/cache/utils.d.ts +9 -0
- package/out/cache/utils.js +114 -0
- package/out/cache/writeAssertionCache.d.ts +42 -0
- package/out/cache/writeAssertionCache.js +141 -0
- package/out/cli/cli.d.ts +2 -0
- package/out/cli/cli.js +25 -0
- package/out/cli/precache.d.ts +1 -0
- package/out/cli/precache.js +7 -0
- package/out/cli/shared.d.ts +1 -0
- package/out/cli/shared.js +1 -0
- package/out/cli/stats.d.ts +1 -0
- package/out/cli/stats.js +54 -0
- package/out/cli/trace.d.ts +1 -0
- package/out/cli/trace.js +37 -0
- package/out/config.d.ts +42 -0
- package/out/config.js +94 -0
- package/out/fixtures.d.ts +6 -0
- package/out/fixtures.js +29 -0
- package/out/index.d.ts +9 -0
- package/out/index.js +8 -0
- package/out/tsVersioning.d.ts +45 -0
- package/out/tsVersioning.js +119 -0
- package/out/utils.d.ts +15 -0
- package/out/utils.js +36 -0
- package/package.json +48 -0
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { BenchContext } from "./bench.js";
|
|
2
|
+
import { type MarkMeasure, type Measure, type MeasureComparison } from "./measure.js";
|
|
3
|
+
export declare const queueBaselineUpdateIfNeeded: (updated: Measure | MarkMeasure, baseline: Measure | MarkMeasure | undefined, ctx: BenchContext) => void;
|
|
4
|
+
/** Pretty print comparison and set the process.exitCode to 1 if delta threshold is exceeded */
|
|
5
|
+
export declare const compareToBaseline: (result: MeasureComparison, ctx: BenchContext) => void;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { snapshot } from "@ark/util";
|
|
2
|
+
import { AssertionError } from "node:assert";
|
|
3
|
+
import process from "node:process";
|
|
4
|
+
import { queueSnapshotUpdate, writeSnapshotUpdatesOnExit } from "../cache/snapshots.js";
|
|
5
|
+
import { stringifyMeasure } from "./measure.js";
|
|
6
|
+
export const queueBaselineUpdateIfNeeded = (updated, baseline, ctx) => {
|
|
7
|
+
// If we already have a baseline and the user didn't pass an update flag, do nothing
|
|
8
|
+
if (baseline && !ctx.cfg.updateSnapshots)
|
|
9
|
+
return;
|
|
10
|
+
const serializedValue = snapshot(updated);
|
|
11
|
+
if (!ctx.lastSnapCallPosition) {
|
|
12
|
+
throw new Error(`Unable to update baseline for ${ctx.qualifiedName} ('lastSnapCallPosition' was unset).`);
|
|
13
|
+
}
|
|
14
|
+
queueSnapshotUpdate({
|
|
15
|
+
position: ctx.lastSnapCallPosition,
|
|
16
|
+
serializedValue,
|
|
17
|
+
snapFunctionName: ctx.kind,
|
|
18
|
+
baselinePath: ctx.qualifiedPath
|
|
19
|
+
});
|
|
20
|
+
if (ctx.kind === "types")
|
|
21
|
+
writeSnapshotUpdatesOnExit();
|
|
22
|
+
};
|
|
23
|
+
/** Pretty print comparison and set the process.exitCode to 1 if delta threshold is exceeded */
|
|
24
|
+
export const compareToBaseline = (result, ctx) => {
|
|
25
|
+
console.log(`⛳ Result: ${stringifyMeasure(result.updated)}`);
|
|
26
|
+
if (result.baseline && !ctx.cfg.updateSnapshots) {
|
|
27
|
+
console.log(`🎯 Baseline: ${stringifyMeasure(result.baseline)}`);
|
|
28
|
+
const delta = ((result.updated[0] - result.baseline[0]) / result.baseline[0]) * 100;
|
|
29
|
+
const formattedDelta = `${delta.toFixed(2)}%`;
|
|
30
|
+
if (delta > ctx.cfg.benchPercentThreshold)
|
|
31
|
+
handlePositiveDelta(formattedDelta, ctx);
|
|
32
|
+
else if (delta < -ctx.cfg.benchPercentThreshold)
|
|
33
|
+
handleNegativeDelta(formattedDelta, ctx);
|
|
34
|
+
else
|
|
35
|
+
console.log(`📊 Delta: ${delta > 0 ? "+" : ""}${formattedDelta}`);
|
|
36
|
+
// add an extra newline
|
|
37
|
+
console.log();
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
const handlePositiveDelta = (formattedDelta, ctx) => {
|
|
41
|
+
const message = `'${ctx.qualifiedName}' exceeded baseline by ${formattedDelta} (threshold is ${ctx.cfg.benchPercentThreshold}%).`;
|
|
42
|
+
console.error(`📈 ${message}`);
|
|
43
|
+
if (ctx.cfg.benchErrorOnThresholdExceeded) {
|
|
44
|
+
const errorSummary = `❌ ${message}`;
|
|
45
|
+
if (ctx.kind === "instantiations")
|
|
46
|
+
throw new AssertionError({ message: errorSummary });
|
|
47
|
+
else {
|
|
48
|
+
process.exitCode = 1;
|
|
49
|
+
// Summarize failures at the end of output
|
|
50
|
+
process.on("exit", () => {
|
|
51
|
+
console.error(errorSummary);
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
const handleNegativeDelta = (formattedDelta, ctx) => {
|
|
57
|
+
console.log(
|
|
58
|
+
// Remove the leading negative when formatting our delta
|
|
59
|
+
`📉 ${ctx.qualifiedName} was under baseline by ${formattedDelta.slice(1)}! Consider setting a new baseline.`);
|
|
60
|
+
};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { type SourcePosition } from "@ark/fs";
|
|
2
|
+
import { type ParsedAttestConfig } from "../config.js";
|
|
3
|
+
import { type MarkMeasure, type Measure, type TimeUnit } from "./measure.js";
|
|
4
|
+
import { type BenchTypeAssertions } from "./type.js";
|
|
5
|
+
export type StatName = keyof typeof stats;
|
|
6
|
+
export type TimeAssertionName = StatName | "mark";
|
|
7
|
+
export declare const bench: <Fn extends BenchableFunction>(name: string, fn: Fn, options?: BenchOptions) => InitialBenchAssertions<Fn>;
|
|
8
|
+
export declare const stats: {
|
|
9
|
+
mean: (callTimes: number[]) => number;
|
|
10
|
+
median: (callTimes: number[]) => number;
|
|
11
|
+
};
|
|
12
|
+
export declare class BenchAssertions<Fn extends BenchableFunction, NextAssertions = BenchTypeAssertions, ReturnedAssertions = Fn extends () => Promise<void> ? Promise<NextAssertions> : NextAssertions> {
|
|
13
|
+
private fn;
|
|
14
|
+
private ctx;
|
|
15
|
+
private label;
|
|
16
|
+
private lastCallTimes;
|
|
17
|
+
constructor(fn: Fn, ctx: BenchContext);
|
|
18
|
+
private applyCallTimeHooks;
|
|
19
|
+
private callTimesSync;
|
|
20
|
+
private callTimesAsync;
|
|
21
|
+
private createAssertion;
|
|
22
|
+
private markAssertion;
|
|
23
|
+
private getNextAssertions;
|
|
24
|
+
private createStatMethod;
|
|
25
|
+
private addUnhandledBenchException;
|
|
26
|
+
median(baseline?: Measure<TimeUnit>): ReturnedAssertions;
|
|
27
|
+
mean(baseline?: Measure<TimeUnit>): ReturnedAssertions;
|
|
28
|
+
mark(baseline?: MarkMeasure): ReturnedAssertions;
|
|
29
|
+
}
|
|
30
|
+
export type UntilOptions = {
|
|
31
|
+
ms?: number;
|
|
32
|
+
count?: number;
|
|
33
|
+
};
|
|
34
|
+
export type BaseBenchOptions = {
|
|
35
|
+
until?: UntilOptions;
|
|
36
|
+
};
|
|
37
|
+
export type BenchOptions = BaseBenchOptions & {
|
|
38
|
+
hooks?: {
|
|
39
|
+
beforeCall?: () => void;
|
|
40
|
+
afterCall?: () => void;
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
export type InternalBenchOptions = BenchOptions & {
|
|
44
|
+
fakeCallMs?: number | "count";
|
|
45
|
+
};
|
|
46
|
+
export type BenchContext = {
|
|
47
|
+
qualifiedPath: string[];
|
|
48
|
+
qualifiedName: string;
|
|
49
|
+
options: InternalBenchOptions;
|
|
50
|
+
cfg: ParsedAttestConfig;
|
|
51
|
+
benchCallPosition: SourcePosition;
|
|
52
|
+
lastSnapCallPosition: SourcePosition | undefined;
|
|
53
|
+
isAsync: boolean;
|
|
54
|
+
kind: TimeAssertionName | "types" | "instantiations";
|
|
55
|
+
};
|
|
56
|
+
export type BenchableFunction = () => unknown | Promise<unknown>;
|
|
57
|
+
export type InitialBenchAssertions<Fn extends BenchableFunction> = BenchAssertions<Fn> & BenchTypeAssertions;
|
|
58
|
+
export declare const getBenchCtx: (qualifiedPath: string[], isAsync?: boolean, options?: BenchOptions) => BenchContext;
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { caller } from "@ark/fs";
|
|
2
|
+
import { performance } from "node:perf_hooks";
|
|
3
|
+
import { ensureCacheDirs, getConfig } from "../config.js";
|
|
4
|
+
import { chainableNoOpProxy } from "../utils.js";
|
|
5
|
+
import { await1K } from "./await1k.js";
|
|
6
|
+
import { compareToBaseline, queueBaselineUpdateIfNeeded } from "./baseline.js";
|
|
7
|
+
import { call1K } from "./call1k.js";
|
|
8
|
+
import { createTimeComparison, createTimeMeasure } from "./measure.js";
|
|
9
|
+
import { createBenchTypeAssertion } from "./type.js";
|
|
10
|
+
export const bench = (name, fn, options = {}) => {
|
|
11
|
+
const qualifiedPath = [...currentSuitePath, name];
|
|
12
|
+
console.log(`🏌️ ${qualifiedPath.join("/")}`);
|
|
13
|
+
const ctx = getBenchCtx(qualifiedPath, fn.constructor.name === "AsyncFunction", options);
|
|
14
|
+
ctx.benchCallPosition = caller();
|
|
15
|
+
ensureCacheDirs();
|
|
16
|
+
if (typeof ctx.cfg.filter === "string" &&
|
|
17
|
+
!qualifiedPath.includes(ctx.cfg.filter))
|
|
18
|
+
return chainableNoOpProxy;
|
|
19
|
+
else if (Array.isArray(ctx.cfg.filter) &&
|
|
20
|
+
ctx.cfg.filter.some((segment, i) => segment !== qualifiedPath[i]))
|
|
21
|
+
return chainableNoOpProxy;
|
|
22
|
+
const assertions = new BenchAssertions(fn, ctx);
|
|
23
|
+
Object.assign(assertions, createBenchTypeAssertion(ctx));
|
|
24
|
+
return assertions;
|
|
25
|
+
};
|
|
26
|
+
export const stats = {
|
|
27
|
+
mean: (callTimes) => {
|
|
28
|
+
const totalCallMs = callTimes.reduce((sum, duration) => sum + duration, 0);
|
|
29
|
+
return totalCallMs / callTimes.length;
|
|
30
|
+
},
|
|
31
|
+
median: (callTimes) => {
|
|
32
|
+
const middleIndex = Math.floor(callTimes.length / 2);
|
|
33
|
+
const ms = callTimes.length % 2 === 0 ?
|
|
34
|
+
(callTimes[middleIndex - 1] + callTimes[middleIndex]) / 2
|
|
35
|
+
: callTimes[middleIndex];
|
|
36
|
+
return ms;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
class ResultCollector {
|
|
40
|
+
ctx;
|
|
41
|
+
results = [];
|
|
42
|
+
benchStart = performance.now();
|
|
43
|
+
bounds;
|
|
44
|
+
lastInvocationStart;
|
|
45
|
+
constructor(ctx) {
|
|
46
|
+
this.ctx = ctx;
|
|
47
|
+
// By default, will run for either 5 seconds or 100_000 call sets (of 1000 calls), whichever comes first
|
|
48
|
+
this.bounds = {
|
|
49
|
+
ms: 5000,
|
|
50
|
+
count: 100_000,
|
|
51
|
+
...ctx.options.until
|
|
52
|
+
};
|
|
53
|
+
this.lastInvocationStart = -1;
|
|
54
|
+
}
|
|
55
|
+
start() {
|
|
56
|
+
this.ctx.options.hooks?.beforeCall?.();
|
|
57
|
+
this.lastInvocationStart = performance.now();
|
|
58
|
+
}
|
|
59
|
+
stop() {
|
|
60
|
+
this.results.push((performance.now() - this.lastInvocationStart) / 1000);
|
|
61
|
+
this.ctx.options.hooks?.afterCall?.();
|
|
62
|
+
}
|
|
63
|
+
done() {
|
|
64
|
+
const metMsTarget = performance.now() - this.benchStart >= this.bounds.ms;
|
|
65
|
+
const metCountTarget = this.results.length >= this.bounds.count;
|
|
66
|
+
return metMsTarget || metCountTarget;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const loopCalls = (fn, ctx) => {
|
|
70
|
+
const collector = new ResultCollector(ctx);
|
|
71
|
+
while (!collector.done()) {
|
|
72
|
+
collector.start();
|
|
73
|
+
// we use a function like this to make 1k explicit calls to the function
|
|
74
|
+
// to avoid certain optimizations V8 makes when looping
|
|
75
|
+
call1K(fn);
|
|
76
|
+
collector.stop();
|
|
77
|
+
}
|
|
78
|
+
return collector.results;
|
|
79
|
+
};
|
|
80
|
+
const loopAsyncCalls = async (fn, ctx) => {
|
|
81
|
+
const collector = new ResultCollector(ctx);
|
|
82
|
+
while (!collector.done()) {
|
|
83
|
+
collector.start();
|
|
84
|
+
await await1K(fn);
|
|
85
|
+
collector.stop();
|
|
86
|
+
}
|
|
87
|
+
return collector.results;
|
|
88
|
+
};
|
|
89
|
+
export class BenchAssertions {
|
|
90
|
+
fn;
|
|
91
|
+
ctx;
|
|
92
|
+
label;
|
|
93
|
+
lastCallTimes;
|
|
94
|
+
constructor(fn, ctx) {
|
|
95
|
+
this.fn = fn;
|
|
96
|
+
this.ctx = ctx;
|
|
97
|
+
this.label = `Call: ${ctx.qualifiedName}`;
|
|
98
|
+
}
|
|
99
|
+
applyCallTimeHooks() {
|
|
100
|
+
if (this.ctx.options.fakeCallMs !== undefined) {
|
|
101
|
+
const fakeMs = this.ctx.options.fakeCallMs === "count" ?
|
|
102
|
+
this.lastCallTimes.length
|
|
103
|
+
: this.ctx.options.fakeCallMs;
|
|
104
|
+
this.lastCallTimes = this.lastCallTimes.map(() => fakeMs);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
callTimesSync() {
|
|
108
|
+
if (!this.lastCallTimes) {
|
|
109
|
+
this.lastCallTimes = loopCalls(this.fn, this.ctx);
|
|
110
|
+
this.lastCallTimes.sort();
|
|
111
|
+
}
|
|
112
|
+
this.applyCallTimeHooks();
|
|
113
|
+
return this.lastCallTimes;
|
|
114
|
+
}
|
|
115
|
+
async callTimesAsync() {
|
|
116
|
+
if (!this.lastCallTimes) {
|
|
117
|
+
this.lastCallTimes = await loopAsyncCalls(this.fn, this.ctx);
|
|
118
|
+
this.lastCallTimes.sort();
|
|
119
|
+
}
|
|
120
|
+
this.applyCallTimeHooks();
|
|
121
|
+
return this.lastCallTimes;
|
|
122
|
+
}
|
|
123
|
+
createAssertion(name, baseline, callTimes) {
|
|
124
|
+
if (name === "mark")
|
|
125
|
+
return this.markAssertion(baseline, callTimes);
|
|
126
|
+
const ms = stats[name](callTimes);
|
|
127
|
+
const comparison = createTimeComparison(ms, baseline);
|
|
128
|
+
console.group(`${this.label} (${name}):`);
|
|
129
|
+
compareToBaseline(comparison, this.ctx);
|
|
130
|
+
console.groupEnd();
|
|
131
|
+
queueBaselineUpdateIfNeeded(createTimeMeasure(ms), baseline, {
|
|
132
|
+
...this.ctx,
|
|
133
|
+
kind: name
|
|
134
|
+
});
|
|
135
|
+
return this.getNextAssertions();
|
|
136
|
+
}
|
|
137
|
+
markAssertion(baseline, callTimes) {
|
|
138
|
+
console.group(`${this.label}:`);
|
|
139
|
+
const markEntries = (baseline ?
|
|
140
|
+
Object.entries(baseline)
|
|
141
|
+
// If nothing was passed, gather all available baselines by setting their values to undefined.
|
|
142
|
+
: Object.entries(stats).map(([kind]) => [kind, undefined]));
|
|
143
|
+
const markResults = Object.fromEntries(markEntries.map(([kind, kindBaseline]) => {
|
|
144
|
+
console.group(kind);
|
|
145
|
+
const ms = stats[kind](callTimes);
|
|
146
|
+
const comparison = createTimeComparison(ms, kindBaseline);
|
|
147
|
+
compareToBaseline(comparison, this.ctx);
|
|
148
|
+
console.groupEnd();
|
|
149
|
+
return [kind, comparison.updated];
|
|
150
|
+
}));
|
|
151
|
+
console.groupEnd();
|
|
152
|
+
queueBaselineUpdateIfNeeded(markResults, baseline, {
|
|
153
|
+
...this.ctx,
|
|
154
|
+
kind: "mark"
|
|
155
|
+
});
|
|
156
|
+
return this.getNextAssertions();
|
|
157
|
+
}
|
|
158
|
+
getNextAssertions() {
|
|
159
|
+
return createBenchTypeAssertion(this.ctx);
|
|
160
|
+
}
|
|
161
|
+
createStatMethod(name, baseline) {
|
|
162
|
+
if (this.ctx.isAsync) {
|
|
163
|
+
return new Promise(resolve => {
|
|
164
|
+
this.callTimesAsync().then(callTimes => {
|
|
165
|
+
resolve(this.createAssertion(name, baseline, callTimes));
|
|
166
|
+
}, e => {
|
|
167
|
+
this.addUnhandledBenchException(e);
|
|
168
|
+
resolve(chainableNoOpProxy);
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
let assertions = chainableNoOpProxy;
|
|
173
|
+
try {
|
|
174
|
+
assertions = this.createAssertion(name, baseline, this.callTimesSync());
|
|
175
|
+
}
|
|
176
|
+
catch (e) {
|
|
177
|
+
this.addUnhandledBenchException(e);
|
|
178
|
+
}
|
|
179
|
+
return assertions;
|
|
180
|
+
}
|
|
181
|
+
addUnhandledBenchException(reason) {
|
|
182
|
+
const message = `Bench ${this.ctx.qualifiedName} threw during execution:\n${String(reason)}`;
|
|
183
|
+
console.error(message);
|
|
184
|
+
unhandledExceptionMessages.push(message);
|
|
185
|
+
}
|
|
186
|
+
median(baseline) {
|
|
187
|
+
this.ctx.lastSnapCallPosition = caller();
|
|
188
|
+
const assertions = this.createStatMethod("median", baseline);
|
|
189
|
+
return assertions;
|
|
190
|
+
}
|
|
191
|
+
mean(baseline) {
|
|
192
|
+
this.ctx.lastSnapCallPosition = caller();
|
|
193
|
+
return this.createStatMethod("mean", baseline);
|
|
194
|
+
}
|
|
195
|
+
mark(baseline) {
|
|
196
|
+
this.ctx.lastSnapCallPosition = caller();
|
|
197
|
+
return this.createStatMethod("mark", baseline);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
const unhandledExceptionMessages = [];
|
|
201
|
+
const currentSuitePath = [];
|
|
202
|
+
process.on("beforeExit", () => {
|
|
203
|
+
if (unhandledExceptionMessages.length) {
|
|
204
|
+
console.error(`${unhandledExceptionMessages.length} unhandled exception(s) occurred during your benches (see details above).`);
|
|
205
|
+
process.exit(1);
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
export const getBenchCtx = (qualifiedPath, isAsync = false, options = {}) => ({
|
|
209
|
+
qualifiedPath,
|
|
210
|
+
qualifiedName: qualifiedPath.join("/"),
|
|
211
|
+
options,
|
|
212
|
+
cfg: getConfig(),
|
|
213
|
+
benchCallPosition: caller(),
|
|
214
|
+
lastSnapCallPosition: undefined,
|
|
215
|
+
isAsync
|
|
216
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const call1K: (fn: () => void) => void;
|