@ashishjain15491/tapcheck 0.0.0-stage → 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.
- package/CHANGELOG.md +87 -0
- package/LICENSE +21 -0
- package/README.md +190 -2
- package/dist/auth.d.ts +5 -0
- package/dist/auth.js +100 -0
- package/dist/browser.d.ts +143 -0
- package/dist/browser.js +237 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +321 -0
- package/dist/config.d.ts +169 -0
- package/dist/config.js +369 -0
- package/dist/coverage.d.ts +17 -0
- package/dist/coverage.js +56 -0
- package/dist/flow.d.ts +193 -0
- package/dist/flow.js +512 -0
- package/dist/jev.d.ts +48 -0
- package/dist/jev.js +89 -0
- package/dist/parts.d.ts +65 -0
- package/dist/parts.js +157 -0
- package/dist/questions.d.ts +66 -0
- package/dist/questions.js +203 -0
- package/dist/report.d.ts +29 -0
- package/dist/report.js +59 -0
- package/dist/routes.d.ts +18 -0
- package/dist/routes.js +54 -0
- package/dist/stub.d.ts +51 -0
- package/dist/stub.js +244 -0
- package/dist/suites/a11y.d.ts +3 -0
- package/dist/suites/a11y.js +73 -0
- package/dist/suites/audit.d.ts +2 -0
- package/dist/suites/audit.js +440 -0
- package/dist/suites/code.d.ts +10 -0
- package/dist/suites/code.js +48 -0
- package/dist/suites/contract.d.ts +5 -0
- package/dist/suites/contract.js +79 -0
- package/dist/suites/crawl.d.ts +2 -0
- package/dist/suites/crawl.js +135 -0
- package/dist/suites/interact.d.ts +2 -0
- package/dist/suites/interact.js +319 -0
- package/dist/suites/security.d.ts +12 -0
- package/dist/suites/security.js +134 -0
- package/dist/suites/usability.d.ts +3 -0
- package/dist/suites/usability.js +205 -0
- package/dist/suites/ux.d.ts +6 -0
- package/dist/suites/ux.js +183 -0
- package/package.json +61 -5
- package/schema/tapcheck.schema.json +368 -0
package/dist/flow.js
ADDED
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
/*
|
|
10
|
+
* Custom flows: the journeys only this app has (sign up, check out, invite a colleague), written by the project as
|
|
11
|
+
* TS/JS files that tapcheck.yml names with `flows:`. Each file's default export is a Flow; it runs as its own part,
|
|
12
|
+
* flow-<name>, on one side:
|
|
13
|
+
*
|
|
14
|
+
* import type { Flow } from 'tapcheck';
|
|
15
|
+
* export default {
|
|
16
|
+
* name: 'Contact',
|
|
17
|
+
* run: async (t) => {
|
|
18
|
+
* const page = await t.goto('/contact');
|
|
19
|
+
* await t.step('the form has a message field', async () => { t.expect(await page.getByLabel('Message').count(), 'no field labelled Message'); });
|
|
20
|
+
* },
|
|
21
|
+
* } satisfies Flow;
|
|
22
|
+
*
|
|
23
|
+
* Each step is one finding: pass, or fail with what was thrown, a screenshot and the page's console errors (a step that
|
|
24
|
+
* returns `{ warn: '…' }` is a warning instead); the flow carries on after a failed step. A flow that takes longer than
|
|
25
|
+
* its `timeout` (seconds, default 3600) fails: nothing it does after that is recorded, t.signal is aborted, and what it
|
|
26
|
+
* gave t.cleanup(fn) runs (as it does when the flow ends). With `parallel` above 1 a side's flows run that many at a time;
|
|
27
|
+
* `serial: true` in a flow's export runs it alone, for a flow that changes what the others read. t.note(name, detail, 'warn' | 'info' | 'fail') records a
|
|
28
|
+
* finding without a step. Unlike the suites, a flow may click anything and change data: run it against a copy
|
|
29
|
+
* you can reset. t.jev() and t.mail.judge() ask Jev to look at the current page or at an email; with JEV=off or no key
|
|
30
|
+
* they record that they were skipped and return null, so a flow that calls them still runs everywhere.
|
|
31
|
+
*/
|
|
32
|
+
import { globSync, mkdirSync } from 'node:fs';
|
|
33
|
+
import { resolve } from 'node:path';
|
|
34
|
+
import { pathToFileURL } from 'node:url';
|
|
35
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
36
|
+
import { abs, context, guard, host, reach, REFUSED, settle, slices, slug, watch } from './browser.js';
|
|
37
|
+
import { isLocal } from './config.js';
|
|
38
|
+
import * as jev from './jev.js';
|
|
39
|
+
import { EMAIL, VISUAL, YES_IS_DEFECT } from './questions.js';
|
|
40
|
+
/** For a flow's own questions to t.jev(), t.ask() and t.mail.judge(), and tapcheck's own sets to start from. */
|
|
41
|
+
export { choice, noul, score } from '@typesafe-ai/sdk';
|
|
42
|
+
export { EMAIL, VISUAL } from './questions.js';
|
|
43
|
+
// Set while a cleanup runs, so its t.* calls work past the timeout while the abandoned run()'s, in another async context,
|
|
44
|
+
// don't. One token per cleanup, switched off when its 60 s are up, so a cleanup that hangs past them loses it too.
|
|
45
|
+
const inCleanup = new AsyncLocalStorage();
|
|
46
|
+
/** What a flow's run() is handed. */
|
|
47
|
+
export class T {
|
|
48
|
+
r;
|
|
49
|
+
flow;
|
|
50
|
+
stubUrl;
|
|
51
|
+
pages = new Map(); // "<viewport> <signed in>" → page
|
|
52
|
+
fresh = []; // contexts of t.page({ fresh: true }), closed with the flow
|
|
53
|
+
signedOut = new WeakSet();
|
|
54
|
+
errors = new WeakMap();
|
|
55
|
+
current; // the page last handed out: goto() drives it, a failed step shows it
|
|
56
|
+
cleanups = [];
|
|
57
|
+
shots = 0;
|
|
58
|
+
dead = false; // past the flow's timeout: what it still records is dropped
|
|
59
|
+
abort = new AbortController();
|
|
60
|
+
/** Aborted when the flow runs out of time: pass it to long waits of your own, or check `t.signal.aborted` in a loop. */
|
|
61
|
+
signal = this.abort.signal;
|
|
62
|
+
constructor(r, flow, stubUrl) {
|
|
63
|
+
this.r = r;
|
|
64
|
+
this.flow = flow;
|
|
65
|
+
this.stubUrl = stubUrl;
|
|
66
|
+
}
|
|
67
|
+
/** The run's folder, for files of the flow's own (a payload log, a list it made). */
|
|
68
|
+
get dir() { return this.r.dir; }
|
|
69
|
+
record(f) { if (this.live())
|
|
70
|
+
this.r.record(f); }
|
|
71
|
+
live() { return !this.dead || inCleanup.getStore()?.on === true; }
|
|
72
|
+
/** Stops the flow at its timeout: later findings are dropped and `t.signal` is aborted. */
|
|
73
|
+
kill(why) { this.dead = true; this.abort.abort(new Error(why)); }
|
|
74
|
+
/** Past the timeout every t.* call but a cleanup's throws, so the abandoned run() stops at its next one. */
|
|
75
|
+
alive() { if (!this.live())
|
|
76
|
+
throw this.signal.reason; }
|
|
77
|
+
/** Runs `fn` when the flow ends, also when it fails or runs out of time (each one gets 60 s): put back what it changed. */
|
|
78
|
+
cleanup(fn) { this.alive(); this.cleanups.push(fn); }
|
|
79
|
+
/**
|
|
80
|
+
* Runs the cleanups, last added first; one that throws or hangs is a warning. Past the timeout the flow's pages are
|
|
81
|
+
* closed first, so the abandoned run() can't drive one while a cleanup works: a cleanup's t.page() opens new ones.
|
|
82
|
+
* Only what a cleanup awaits itself carries its t.* rights: a Playwright handler it adds (page.on) runs outside them
|
|
83
|
+
* unless wrapped with AsyncResource.bind (node:async_hooks).
|
|
84
|
+
*/
|
|
85
|
+
async finish() {
|
|
86
|
+
if (this.dead) {
|
|
87
|
+
await this.close();
|
|
88
|
+
this.pages.clear();
|
|
89
|
+
this.fresh = [];
|
|
90
|
+
this.current = undefined;
|
|
91
|
+
}
|
|
92
|
+
for (let fn; (fn = this.cleanups.pop());) {
|
|
93
|
+
let timer;
|
|
94
|
+
const token = { on: true };
|
|
95
|
+
const cap = new Promise((_, no) => { timer = setTimeout(() => no(new Error('it took over 60 s')), 60_000); });
|
|
96
|
+
try {
|
|
97
|
+
await Promise.race([inCleanup.run(token, () => Promise.resolve().then(fn)), cap]);
|
|
98
|
+
}
|
|
99
|
+
catch (e) {
|
|
100
|
+
this.r.record({ suite: this.flow.part, where: this.flow.name, check: 'cleanup ran', status: 'warn', detail: String(e.message ?? e).slice(0, 300) });
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
token.on = false;
|
|
104
|
+
clearTimeout(timer);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
this.dead = true; // the flow is over: an abandoned run() that wakes up later records nothing
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* A page on the flow's side, signed in with the side's session (`{ auth: false }`: signed out), at the first viewport
|
|
111
|
+
* or the one `viewport` names (`{ viewport: 'mobile' }`, a name from the config's viewports). One of each is kept, and
|
|
112
|
+
* the page handed out last is the current one: t.goto() and t.jev() act on it. `{ fresh: true }` gives a new page in
|
|
113
|
+
* a context of its own every time (cookies and storage its own too), for a second visitor or a sign-in of the flow's own;
|
|
114
|
+
* it is the current page too, until t.page() or t.use() hands out another.
|
|
115
|
+
*/
|
|
116
|
+
async page(opts = {}) {
|
|
117
|
+
this.alive();
|
|
118
|
+
const auth = opts.auth !== false, all = this.r.cfg.viewports;
|
|
119
|
+
const vp = opts.viewport === undefined ? all[0] : all.find((v) => v.name === opts.viewport);
|
|
120
|
+
if (!vp)
|
|
121
|
+
throw new Error(`t.page: no viewport is called "${opts.viewport}" (viewports: ${all.map((v) => v.name).join(', ')}).`);
|
|
122
|
+
const open = async () => {
|
|
123
|
+
const ctx = await context(this.r, vp, auth);
|
|
124
|
+
const page = await ctx.newPage().catch(async (e) => { await ctx.close().catch(() => { }); throw e; });
|
|
125
|
+
if (!this.live()) {
|
|
126
|
+
await ctx.close().catch(() => { });
|
|
127
|
+
this.alive();
|
|
128
|
+
} // timed out while it opened: not into the cleanups' cache
|
|
129
|
+
this.errors.set(page, watch(page));
|
|
130
|
+
if (!auth)
|
|
131
|
+
this.signedOut.add(ctx);
|
|
132
|
+
return { ctx, page };
|
|
133
|
+
};
|
|
134
|
+
if (opts.fresh) {
|
|
135
|
+
const { ctx, page } = await open();
|
|
136
|
+
this.fresh.push(ctx);
|
|
137
|
+
return (this.current = page);
|
|
138
|
+
}
|
|
139
|
+
const key = `${vp.name} ${auth}`;
|
|
140
|
+
if (!this.pages.has(key))
|
|
141
|
+
this.pages.set(key, (await open()).page);
|
|
142
|
+
return (this.current = this.pages.get(key));
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Makes `page` the current one: t.goto(), t.jev() and a failed step's screenshot act on it. For a page t.page() handed
|
|
146
|
+
* out earlier (back to the first visitor after a second one), or a tab the app opened itself (`context.waitForEvent('page')`).
|
|
147
|
+
*/
|
|
148
|
+
use(page) {
|
|
149
|
+
this.alive();
|
|
150
|
+
if (!this.errors.has(page))
|
|
151
|
+
this.errors.set(page, watch(page));
|
|
152
|
+
return (this.current = page);
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Opens a path of the side (or a full URL) on the current page and waits for it to settle. On a signed-in page, being
|
|
156
|
+
* sent to sign in (`loginPaths`) when the path isn't a sign-in page throws: the side's session has ended. A flow that
|
|
157
|
+
* expects to be sent there (after signing out, or to check a page is refused) passes `{ guard: false }`.
|
|
158
|
+
*/
|
|
159
|
+
async goto(path, opts = {}) {
|
|
160
|
+
this.alive();
|
|
161
|
+
const page = this.current ?? await this.page();
|
|
162
|
+
const url = abs(this.r, path);
|
|
163
|
+
await page.goto(url, { waitUntil: 'domcontentloaded' });
|
|
164
|
+
await settle(page);
|
|
165
|
+
if (opts.guard !== false && !this.signedOut.has(page.context()))
|
|
166
|
+
guard(this.r, new URL(url).pathname, page.url());
|
|
167
|
+
return page;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Counts a request to the app the flow made itself (page.request, fetch) as reached, for hits.json and COVERAGE=1.
|
|
171
|
+
* Pass its answer's status, and one the app refused (401, 403, 405) or didn't find (404) isn't counted, as in the browser.
|
|
172
|
+
*/
|
|
173
|
+
reach(method, url, status) {
|
|
174
|
+
this.alive();
|
|
175
|
+
const u = new URL(abs(this.r, url));
|
|
176
|
+
if (status !== undefined && REFUSED.includes(status))
|
|
177
|
+
return;
|
|
178
|
+
if (host(u.href) === host(this.r.side.baseUrl))
|
|
179
|
+
reach(this.r, `${method.toUpperCase()} ${u.pathname}`); // another host isn't the app's
|
|
180
|
+
}
|
|
181
|
+
/** Throws `msg` unless `cond` holds. (Not an `asserts` signature: TypeScript refuses those on the untyped `t` of `run: async (t) => …`.) */
|
|
182
|
+
expect(cond, msg) {
|
|
183
|
+
if (!cond)
|
|
184
|
+
throw new Error(msg);
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* One finding: passes when `fn` returns (a string it returns is the detail), fails when it throws; returning
|
|
188
|
+
* `{ warn }` makes it a warning with that detail (it worked, with something to look at). Returns whether it didn't fail.
|
|
189
|
+
*/
|
|
190
|
+
async step(name, fn) {
|
|
191
|
+
this.alive();
|
|
192
|
+
const errors = this.current && this.errors.get(this.current);
|
|
193
|
+
if (errors)
|
|
194
|
+
errors.length = 0;
|
|
195
|
+
const base = { suite: this.flow.part, where: this.flow.name, check: name };
|
|
196
|
+
const t0 = Date.now();
|
|
197
|
+
const done = (mark) => { if (this.live())
|
|
198
|
+
process.stdout.write(` ${this.r.prefix ?? ''}${mark} ${name} (${((Date.now() - t0) / 1000).toFixed(1)} s)\n`); }; // progress, one line a step
|
|
199
|
+
this.r.step = name; // what the step reaches is filed under it (hits.json)
|
|
200
|
+
try {
|
|
201
|
+
const out = await fn();
|
|
202
|
+
if (out && typeof out === 'object') {
|
|
203
|
+
this.record({ ...base, status: 'warn', detail: out.warn });
|
|
204
|
+
done('!');
|
|
205
|
+
}
|
|
206
|
+
else {
|
|
207
|
+
this.record({ ...base, status: 'pass', detail: out || undefined });
|
|
208
|
+
done('✓');
|
|
209
|
+
}
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
catch (e) {
|
|
213
|
+
const page = this.current, seen = (page && this.errors.get(page)) ?? [];
|
|
214
|
+
let shot = `${this.r.dir}/shots/${this.flow.part}-${String(++this.shots).padStart(3, '0')}-${slug(name)}.png`;
|
|
215
|
+
mkdirSync(`${this.r.dir}/shots`, { recursive: true });
|
|
216
|
+
if (!page || page.isClosed() || !(await page.screenshot({ path: shot }).then(() => true, () => false)))
|
|
217
|
+
shot = undefined;
|
|
218
|
+
this.record({ ...base, status: 'fail', evidence: shot ? [shot] : undefined,
|
|
219
|
+
detail: [String(e.message ?? e).split('\n').slice(0, 6).join(' ⏎ ').slice(0, 800), seen.length ? `console: ${seen.slice(0, 3).join(' | ').slice(0, 300)}` : ''].filter(Boolean).join(' · ') });
|
|
220
|
+
done('✗');
|
|
221
|
+
return false;
|
|
222
|
+
}
|
|
223
|
+
finally {
|
|
224
|
+
this.r.step = undefined;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/** A finding the flow decides itself: a warning (default), a failure, or info such as a check it skipped and why. */
|
|
228
|
+
note(name, detail, status = 'warn') {
|
|
229
|
+
this.alive();
|
|
230
|
+
this.record({ suite: this.flow.part, where: this.flow.name, check: name, status, detail });
|
|
231
|
+
}
|
|
232
|
+
/** Records that Jev's look at `label` was skipped, and why. */
|
|
233
|
+
skipped(label, why) {
|
|
234
|
+
this.record({ suite: this.flow.part, where: `${this.flow.name} › ${label}`, check: "Jev's look", status: 'info', detail: `skipped (${why})` });
|
|
235
|
+
return null;
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Asks Jev about `state`; one finding per answer. Null, and one finding, when its budget is spent (info) or Jev can't
|
|
239
|
+
* be reached (a warning): a look never stops the flow.
|
|
240
|
+
*/
|
|
241
|
+
async look(label, state, questions, shots) {
|
|
242
|
+
const rec = (check, status, detail) => this.record({ suite: this.flow.part, where: `${this.flow.name} › ${label}`, check, status, detail, evidence: shots.length ? shots : undefined });
|
|
243
|
+
let a;
|
|
244
|
+
try {
|
|
245
|
+
a = await jev.ask(`${this.flow.part}:${label}`, state, questions, shots);
|
|
246
|
+
}
|
|
247
|
+
catch (e) {
|
|
248
|
+
if (e instanceof jev.BudgetReached)
|
|
249
|
+
return this.skipped(label, e.message);
|
|
250
|
+
if (!(e instanceof jev.Unavailable))
|
|
251
|
+
throw e; // the flow's own mistake (a missing image file, say)
|
|
252
|
+
rec("Jev's look", 'warn', `Jev couldn't be asked: ${e.message.slice(0, 300)}`);
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
for (const [k, v] of Object.entries(a)) {
|
|
256
|
+
const name = `jev: ${k.replace(/_/g, ' ')}`;
|
|
257
|
+
if (typeof v?.noul === 'number')
|
|
258
|
+
rec(name, jev.status((YES_IS_DEFECT.includes(k) ? jev.bad : jev.good)(v.noul)), `p=${v.noul.toFixed(2)}`);
|
|
259
|
+
else if (typeof v?.score === 'number')
|
|
260
|
+
rec(name, jev.to10(v.score) >= jev.MIN_SCORE ? 'pass' : 'warn', `${jev.to10(v.score)}/10`);
|
|
261
|
+
else
|
|
262
|
+
rec(name, 'info', JSON.stringify(v?.choice ?? v).slice(0, 200));
|
|
263
|
+
}
|
|
264
|
+
return a;
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Jev's look at the current page: screenshots of it (up to three screens, top to bottom) and the visual questions
|
|
268
|
+
* (loaded, no error, overlap, clipping, raw keys, alignment), or your own `questions` about `screenshots` (built with
|
|
269
|
+
* the TypeSafe SDK's noul, score and choice). Each answer is a finding of the flow, and an unsure one a warning. A
|
|
270
|
+
* yes-or-no question of your own passes on yes; a score passes from 7 of 10 and is a warning below; any other answer is
|
|
271
|
+
* recorded as info. The page is looked at once it has settled. The answers are returned for the flow's own checks; null when Jev is off or over its budget.
|
|
272
|
+
*/
|
|
273
|
+
async jev(label, questions = VISUAL) {
|
|
274
|
+
this.alive();
|
|
275
|
+
if (jev.whyOff())
|
|
276
|
+
return this.skipped(label, jev.whyOff());
|
|
277
|
+
const page = this.current ?? await this.page();
|
|
278
|
+
const vh = page.viewportSize()?.height ?? 800;
|
|
279
|
+
const shoot = async () => {
|
|
280
|
+
await settle(page);
|
|
281
|
+
// With a dialog open only the screen is looked at: the page behind it scrolled into slices would be the same shot again.
|
|
282
|
+
const height = await page.evaluate(() => [...document.querySelectorAll('dialog[open], [role=dialog][aria-modal=true], [role=alertdialog]')].some((d) => {
|
|
283
|
+
if (d.tagName === 'DIALOG' && !d.matches(':modal'))
|
|
284
|
+
return false; // dialog.show(): a banner, not modal
|
|
285
|
+
const b = d.getBoundingClientRect();
|
|
286
|
+
return d.checkVisibility({ visibilityProperty: true, opacityProperty: true }) && b.width > 0 && b.bottom > 0 && b.top < innerHeight && b.right > 0 && b.left < innerWidth;
|
|
287
|
+
}) ? 0 : document.documentElement.scrollHeight);
|
|
288
|
+
return slices(this.r, page, `${this.flow.part}-jev-${slug(label)}`, height || vh, vh);
|
|
289
|
+
};
|
|
290
|
+
// A page that reloads itself while it is looked at (after a save, say) throws the look out: look again once it is back.
|
|
291
|
+
const shots = await shoot().catch((e) => { if (!/context was destroyed|navigat/i.test(String(e)))
|
|
292
|
+
throw e; return shoot(); });
|
|
293
|
+
return this.look(label, { screen: label, screenshots: shots.map(jev.img),
|
|
294
|
+
note: shots.length > 1 ? 'The screenshots are consecutive slices of one screen, top to bottom.' : undefined }, questions, shots);
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Jev's answers to `questions` about `state` you describe yourself (text, data; images built with the SDK's image()
|
|
298
|
+
* whose files are `images`): no screenshot is taken. Findings, budget and null as for t.jev().
|
|
299
|
+
*/
|
|
300
|
+
async ask(label, state, questions, images = []) {
|
|
301
|
+
this.alive();
|
|
302
|
+
if (jev.whyOff())
|
|
303
|
+
return this.skipped(label, jev.whyOff());
|
|
304
|
+
return this.look(label, state, questions, images);
|
|
305
|
+
}
|
|
306
|
+
/** Mailpit and the stub: 30 s at most a call, and none past the flow's timeout (but a cleanup's). */
|
|
307
|
+
async api(base, path, method = 'GET', body) {
|
|
308
|
+
this.alive();
|
|
309
|
+
const signal = AbortSignal.any([AbortSignal.timeout(30_000), ...(inCleanup.getStore()?.on ? [] : [this.signal])]);
|
|
310
|
+
const res = await fetch(base + path, { method, signal, headers: body === undefined ? {} : { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
311
|
+
if (!res.ok)
|
|
312
|
+
throw new Error(`${method} ${base}${path} answered ${res.status}`);
|
|
313
|
+
const text = await res.text();
|
|
314
|
+
try {
|
|
315
|
+
return JSON.parse(text);
|
|
316
|
+
}
|
|
317
|
+
catch {
|
|
318
|
+
if (method === 'DELETE')
|
|
319
|
+
return text; // Mailpit's answers "ok"
|
|
320
|
+
throw new Error(`${method} ${base}${path} answered ${res.status} but not with JSON: ${text.slice(0, 80)}`);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
need(u, field) {
|
|
324
|
+
if (!u)
|
|
325
|
+
throw new Error(`This flow uses ${field === 'stub' ? 't.stub' : 't.mail'}, but tapcheck.yml has no ${field}.`);
|
|
326
|
+
return u;
|
|
327
|
+
}
|
|
328
|
+
/** The stub server (src/stub.ts): the outside requests it saw, and how it answers the next ones. */
|
|
329
|
+
get stub() {
|
|
330
|
+
const base = this.need(this.stubUrl, 'stub');
|
|
331
|
+
const call = (path, method, body) => this.api(base, `/_tapcheck/${path}`, method, body);
|
|
332
|
+
return {
|
|
333
|
+
/** Requests seen, oldest first: by host (or parent domain), a part of the path, and from a time (ms) on. */
|
|
334
|
+
requests: (f = {}) => call(`requests?${new URLSearchParams(Object.entries(f).filter(([, v]) => v !== undefined).map(([k, v]) => [k, String(v)]))}`),
|
|
335
|
+
/** Fails the next `times` matching requests (default 1; 0: until clear()). */
|
|
336
|
+
fail: (rule) => call('fail', 'POST', rule),
|
|
337
|
+
/** Answers the next matching request with this, once. */
|
|
338
|
+
reply: (rule) => call('reply', 'POST', rule),
|
|
339
|
+
/** Answers that DNS question with these values from now on (stub.dns); null puts the config's answer back. */
|
|
340
|
+
dns: (name, type, values) => call('dns', 'POST', { name, type, values }),
|
|
341
|
+
/** Forgets the requests seen, the failures, the queued replies and the DNS answers set here. */
|
|
342
|
+
clear: async () => { for (const p of ['requests', 'fail', 'reply', 'dns'])
|
|
343
|
+
await call(p, 'DELETE'); },
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Sends a browser context's requests for hosts that aren't local through the stub, so nothing in the browser reaches a
|
|
348
|
+
* real outside service. Redirects are followed here hop by hop (a browser doesn't hand them back), so the app sending
|
|
349
|
+
* the browser to an outside page (a provider's sign-in or checkout) lands on the stub too.
|
|
350
|
+
*/
|
|
351
|
+
async routeOutside(ctx) {
|
|
352
|
+
const stub = this.need(this.stubUrl, 'stub');
|
|
353
|
+
await ctx.route((u) => /^https?:$/.test(u.protocol), (route) => (async () => {
|
|
354
|
+
const req = route.request();
|
|
355
|
+
if (isLocal(req.url()) && !req.isNavigationRequest())
|
|
356
|
+
return route.fallback();
|
|
357
|
+
const headers = Object.fromEntries(Object.entries(await req.allHeaders()).filter(([k]) => !/^(:|host$|content-length$)/.test(k)));
|
|
358
|
+
let url = req.url(), method = req.method();
|
|
359
|
+
for (let hop = 0;; hop++) {
|
|
360
|
+
const u = new URL(url), local = isLocal(url);
|
|
361
|
+
const res = await route.fetch({ url: local ? url : stub + u.pathname + u.search, method, headers: local ? headers : { ...headers, 'x-forwarded-host': u.host },
|
|
362
|
+
maxRedirects: 0, ...(hop && method === 'GET' ? { postData: '' } : {}) });
|
|
363
|
+
const to = res.status() >= 300 && res.status() < 400 ? res.headers().location : undefined;
|
|
364
|
+
const next = to ? new URL(to, url).href : null;
|
|
365
|
+
if (!next || isLocal(next) || hop === 5)
|
|
366
|
+
return route.fulfill({ response: res });
|
|
367
|
+
if (req.isNavigationRequest()) { // let the browser go there itself, which comes back through this route
|
|
368
|
+
const kept = Object.fromEntries(Object.entries(res.headers()).filter(([k]) => !/^(location|content-length|content-type)$/.test(k)));
|
|
369
|
+
return route.fulfill({ status: 200, headers: kept, contentType: 'text/html', body: `<meta http-equiv="refresh" content="0;url=${next.replace(/"/g, '"')}">` });
|
|
370
|
+
}
|
|
371
|
+
[url, method] = [next, [307, 308].includes(res.status()) ? method : 'GET'];
|
|
372
|
+
}
|
|
373
|
+
})().catch(() => route.abort('failed').catch(() => { }))); // never fall through to the real host
|
|
374
|
+
}
|
|
375
|
+
/** The mail the app sent, read from Mailpit (config `mail.mailpit`). */
|
|
376
|
+
get mail() {
|
|
377
|
+
const base = this.need(this.r.cfg.mail.mailpit, 'mail.mailpit');
|
|
378
|
+
const call = (path, method) => this.api(base, `/api/v1/${path}`, method);
|
|
379
|
+
const search = (f, limit) => {
|
|
380
|
+
const query = [f.to ? `to:"${f.to}"` : '', f.subject ? `subject:"${f.subject}"` : ''].filter(Boolean).join(' ');
|
|
381
|
+
return { query, found: call(query ? `search?limit=${limit}&query=${encodeURIComponent(query)}` : `messages?limit=${limit}`) };
|
|
382
|
+
};
|
|
383
|
+
const read = async (id) => {
|
|
384
|
+
const m = await call(`message/${id}`);
|
|
385
|
+
const html = m.HTML ?? '';
|
|
386
|
+
return { id, subject: m.Subject ?? '', from: m.From?.Address ?? '', to: (m.To ?? []).map((x) => x.Address), html, text: m.Text ?? '',
|
|
387
|
+
links: [...new Set([...html.matchAll(/href="([^"]+)"/g)].map((x) => x[1].replace(/&/g, '&')))],
|
|
388
|
+
headers: await call(`message/${id}/headers`).catch(() => ({})) };
|
|
389
|
+
};
|
|
390
|
+
return {
|
|
391
|
+
/** The newest message to that address and/or with that subject (a part of it), waiting up to timeoutMs (default 30 s) for it. */
|
|
392
|
+
waitFor: async (f = {}) => {
|
|
393
|
+
const until = Date.now() + (f.timeoutMs ?? 30_000);
|
|
394
|
+
for (;;) {
|
|
395
|
+
const { query, found } = search(f, 1);
|
|
396
|
+
const hit = (await found).messages?.[0];
|
|
397
|
+
if (hit)
|
|
398
|
+
return read(hit.ID);
|
|
399
|
+
if (Date.now() > until)
|
|
400
|
+
throw new Error(`No email${query ? ` matching ${query}` : ''} arrived in Mailpit within ${(f.timeoutMs ?? 30_000) / 1000} s.`);
|
|
401
|
+
await new Promise((done) => setTimeout(done, 500));
|
|
402
|
+
}
|
|
403
|
+
},
|
|
404
|
+
/** How many messages are to that address and/or have that subject (a part of either); all of them without a filter. */
|
|
405
|
+
count: async (f = {}) => { const a = await search(f, 1).found; return a.messages_count ?? a.total ?? 0; },
|
|
406
|
+
/** Every such message, newest first, each read in full: at most `limit` (1 to 500, default 500); `limit: 1` is the newest or none. */
|
|
407
|
+
all: async (f = {}) => {
|
|
408
|
+
const limit = f.limit ?? 500;
|
|
409
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 500)
|
|
410
|
+
throw new Error(`t.mail.all: limit must be a whole number from 1 to 500, not ${limit}.`);
|
|
411
|
+
const out = [];
|
|
412
|
+
for (const m of (await search(f, limit).found).messages ?? [])
|
|
413
|
+
out.push(await read(m.ID));
|
|
414
|
+
return out;
|
|
415
|
+
},
|
|
416
|
+
/**
|
|
417
|
+
* Jev's look at an email: its HTML drawn in a page (scripts off) at a computer's and at a phone's width, then asked
|
|
418
|
+
* whether it is laid out properly, has no unfilled placeholder, shows its links and buttons, and reads on a phone
|
|
419
|
+
* (or your own `questions` about `screenshot` and `screenshot_mobile`). Findings and null as for t.jev().
|
|
420
|
+
* ponytail: only the first 1500 px of the email are looked at; slice it if long emails matter.
|
|
421
|
+
*/
|
|
422
|
+
judge: async (m, questions = EMAIL) => {
|
|
423
|
+
const label = `email "${m.subject}"`;
|
|
424
|
+
const off = jev.whyOff() || (m.html.trim() ? '' : 'the email has no HTML part');
|
|
425
|
+
if (off)
|
|
426
|
+
return this.skipped(label, off);
|
|
427
|
+
const ctx = await context(this.r, { name: 'email', width: 700, height: 1000, mobile: false }, false, false, { javaScriptEnabled: false });
|
|
428
|
+
try {
|
|
429
|
+
const page = await ctx.newPage();
|
|
430
|
+
mkdirSync(`${this.r.dir}/shots`, { recursive: true });
|
|
431
|
+
const shots = [];
|
|
432
|
+
for (const [suffix, width] of [['', 700], ['-mobile', 390]]) {
|
|
433
|
+
await page.setViewportSize({ width, height: 1000 });
|
|
434
|
+
await page.setContent(m.html, { waitUntil: 'load' });
|
|
435
|
+
const height = Math.min(1500, Math.max(300, await page.evaluate(() => document.documentElement.scrollHeight)));
|
|
436
|
+
shots.push(`${this.r.dir}/shots/${this.flow.part}-email-${slug(m.subject)}${suffix}.png`);
|
|
437
|
+
await page.screenshot({ path: shots.at(-1), fullPage: true, clip: { x: 0, y: 0, width, height } });
|
|
438
|
+
}
|
|
439
|
+
return await this.look(label, { email_subject: m.subject, screenshot: jev.img(shots[0]), screenshot_mobile: jev.img(shots[1]) }, questions, shots);
|
|
440
|
+
}
|
|
441
|
+
finally {
|
|
442
|
+
await ctx.close().catch(() => { });
|
|
443
|
+
}
|
|
444
|
+
},
|
|
445
|
+
/** Deletes every message in Mailpit. */
|
|
446
|
+
clear: async () => { await call('messages', 'DELETE'); },
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
/** Closes the flow's pages. */
|
|
450
|
+
async close() {
|
|
451
|
+
for (const page of this.pages.values())
|
|
452
|
+
await page.context().close().catch(() => { });
|
|
453
|
+
for (const ctx of this.fresh)
|
|
454
|
+
await ctx.close().catch(() => { });
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
/** Imports every file the `flows` globs match (relative to the config file) and checks each default export. */
|
|
458
|
+
export async function loadFlows(cfg) {
|
|
459
|
+
const out = [], seen = new Set();
|
|
460
|
+
for (const glob of cfg.flows) {
|
|
461
|
+
const files = globSync(glob, { cwd: cfg.root }).sort();
|
|
462
|
+
if (!files.length)
|
|
463
|
+
throw new Error(`tapcheck.yml: flows: "${glob}" matches no file.`);
|
|
464
|
+
for (const file of files) {
|
|
465
|
+
if (seen.has(file))
|
|
466
|
+
continue; // matched by an earlier glob too
|
|
467
|
+
seen.add(file);
|
|
468
|
+
// Node reads a .ts or .js file as CommonJS when the nearest package.json says so, and then `export` is a syntax error.
|
|
469
|
+
const mod = await import(__rewriteRelativeImportExtension(pathToFileURL(resolve(cfg.root, file)).href)).catch((e) => {
|
|
470
|
+
throw new Error(`${file}: ${e.message}${e instanceof SyntaxError ? ' (if the nearest package.json has "type": "commonjs", name flow files .mts or .mjs)' : ''}`);
|
|
471
|
+
});
|
|
472
|
+
const f = mod.default;
|
|
473
|
+
if (!f || typeof f.name !== 'string' || !f.name.trim() || typeof f.run !== 'function')
|
|
474
|
+
throw new Error(`${file}: a flow file needs \`export default { name, side?, run: async (t) => {…} }\`.`);
|
|
475
|
+
const side = f.side ?? cfg.sides[0].name;
|
|
476
|
+
if (!cfg.sides.some((s) => s.name === side))
|
|
477
|
+
throw new Error(`${file}: side "${side}" isn't in sides (${cfg.sides.map((s) => s.name).join(', ')}).`);
|
|
478
|
+
if (f.timeout !== undefined && !(Number.isFinite(f.timeout) && f.timeout > 0))
|
|
479
|
+
throw new Error(`${file}: timeout must be a number of seconds above 0.`);
|
|
480
|
+
if (f.serial !== undefined && typeof f.serial !== 'boolean')
|
|
481
|
+
throw new Error(`${file}: serial must be true or false.`);
|
|
482
|
+
const part = `flow-${slug(f.name).replace(/_/g, '-')}`;
|
|
483
|
+
if (out.some((o) => o.part === part))
|
|
484
|
+
throw new Error(`${file}: another flow is already called "${f.name}" (part ${part}).`);
|
|
485
|
+
out.push({ name: f.name, side, timeout: f.timeout ?? 3600, serial: f.serial ?? false, run: f.run, part });
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
return out;
|
|
489
|
+
}
|
|
490
|
+
/** Runs one flow on its side; whatever it throws outside a step is the caller's to record. */
|
|
491
|
+
export async function runFlow(flow, r, stubUrl) {
|
|
492
|
+
const t = new T(r, flow, stubUrl);
|
|
493
|
+
let timer;
|
|
494
|
+
// A flow stuck on a promise that never settles would otherwise hold up every part after it.
|
|
495
|
+
const limit = new Promise((_, no) => {
|
|
496
|
+
timer = setTimeout(() => {
|
|
497
|
+
const why = `the flow didn't finish within ${flow.timeout} s (raise its timeout if it needs longer)`;
|
|
498
|
+
t.kill(why); // what the abandoned run() still does is no longer recorded
|
|
499
|
+
no(new Error(why));
|
|
500
|
+
}, flow.timeout * 1000);
|
|
501
|
+
});
|
|
502
|
+
const running = flow.run(t);
|
|
503
|
+
running.catch(() => { }); // abandoned at the timeout, it ends by throwing at its next t.* call: not an unhandled rejection
|
|
504
|
+
try {
|
|
505
|
+
await Promise.race([running, limit]);
|
|
506
|
+
}
|
|
507
|
+
finally {
|
|
508
|
+
clearTimeout(timer);
|
|
509
|
+
await t.finish();
|
|
510
|
+
await t.close();
|
|
511
|
+
}
|
|
512
|
+
}
|
package/dist/jev.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { Config } from './config.ts';
|
|
2
|
+
import type { Finding } from './report.ts';
|
|
3
|
+
export declare const YES = 0.7, NO = 0.3, MIN_SCORE = 7;
|
|
4
|
+
export type Verdict = 'pass' | 'FAIL' | 'unsure';
|
|
5
|
+
export declare const good: (p: number) => Verdict;
|
|
6
|
+
export declare const bad: (p: number) => Verdict;
|
|
7
|
+
export declare const to10: (pos: number) => number;
|
|
8
|
+
/** Verdict → finding status: an unsure Jev answer is a warning for a person to look at, never a pass. */
|
|
9
|
+
export declare const status: (v: Verdict) => Finding['status'];
|
|
10
|
+
/** The part of the TypeSafe client this file uses, so a self-check can put a fake in its place. */
|
|
11
|
+
export type Client = {
|
|
12
|
+
systemOne(req: {
|
|
13
|
+
state: any;
|
|
14
|
+
questions: Record<string, any>;
|
|
15
|
+
model?: string;
|
|
16
|
+
}): Promise<{
|
|
17
|
+
answers: any;
|
|
18
|
+
usage: {
|
|
19
|
+
input_tokens: number | null;
|
|
20
|
+
};
|
|
21
|
+
}>;
|
|
22
|
+
};
|
|
23
|
+
export declare class BudgetReached extends Error {
|
|
24
|
+
}
|
|
25
|
+
/** Jev failed or didn't answer twice: the caller may carry on without its answers. */
|
|
26
|
+
export declare class Unavailable extends Error {
|
|
27
|
+
}
|
|
28
|
+
/** The key from the environment, else from a TYPESAFE_API_KEY= line in ./.env; undefined when there is none. */
|
|
29
|
+
export declare function apiKey(): string | undefined;
|
|
30
|
+
/** Why Jev isn't asked in this run ('JEV=off', no key), or '' when it is. */
|
|
31
|
+
export declare const whyOff: () => "" | "JEV=off" | "no TYPESAFE_API_KEY";
|
|
32
|
+
export declare const payloads: unknown[];
|
|
33
|
+
/** Starts a run: its budget and headers, counters and memo cleared. A self-check passes a fake client; nothing then reaches the network. */
|
|
34
|
+
export declare function setup(jev: Config['jev'], fake?: Client): void;
|
|
35
|
+
/** One Jev request. `images` are the files behind the images in `state`: they key the memo and stand in for the bytes in the log. */
|
|
36
|
+
export declare function ask(label: string, state: unknown, questions: Record<string, any>, images: string[], model?: string): Promise<any>;
|
|
37
|
+
export declare const img: (file: string) => import("@typesafe-ai/sdk").Image;
|
|
38
|
+
export declare const spent: () => number;
|
|
39
|
+
export declare const usage: () => {
|
|
40
|
+
tokens: number;
|
|
41
|
+
usd: number;
|
|
42
|
+
budget: number;
|
|
43
|
+
calls: number;
|
|
44
|
+
cached: number;
|
|
45
|
+
avgMs: number;
|
|
46
|
+
};
|
|
47
|
+
/** Every request of the run, as sent (images as file paths; the key and headers are not part of it). */
|
|
48
|
+
export declare const savePayloads: (dir: string) => void;
|
package/dist/jev.js
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The Jev client the ux, usability and audit suites share: one request function with a memo (the same images, state and
|
|
3
|
+
* questions are answered once), a budget that stops the run before it overspends, a log of every payload so any answer
|
|
4
|
+
* can be rerun, and the rules that turn Jev's probabilities and scores into verdicts. Decisions stay in code.
|
|
5
|
+
*/
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
7
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
8
|
+
import { image, TypeSafeClient } from '@typesafe-ai/sdk';
|
|
9
|
+
// ───────────────────────────── verdict rules ─────────────────────────────
|
|
10
|
+
// Noul: above 0.7 is yes, below 0.3 is no, between is unsure. A Score's position 0–4 maps to 1–10; under 7 is flagged.
|
|
11
|
+
export const YES = 0.7, NO = 0.3, MIN_SCORE = 7;
|
|
12
|
+
export const good = (p) => (p > YES ? 'pass' : p < NO ? 'FAIL' : 'unsure'); // yes is good
|
|
13
|
+
export const bad = (p) => (p < NO ? 'pass' : p > YES ? 'FAIL' : 'unsure'); // yes is a defect
|
|
14
|
+
export const to10 = (pos) => Math.round((1 + (pos * 9) / 4) * 10) / 10;
|
|
15
|
+
/** Verdict → finding status: an unsure Jev answer is a warning for a person to look at, never a pass. */
|
|
16
|
+
export const status = (v) => (v === 'pass' ? 'pass' : v === 'FAIL' ? 'fail' : 'warn');
|
|
17
|
+
// ───────────────────────────── client ─────────────────────────────
|
|
18
|
+
const USD_PER_TOKEN = 0.042 / 1_000_000; // Jev input price; output tokens are free
|
|
19
|
+
// Image support is an opt-in in the SDK (its README, "Images"): this header turns it on. jev.headers is merged over it.
|
|
20
|
+
const IMAGES = { 'TypeSafe-Danger-Zone-Images': 'true' };
|
|
21
|
+
export class BudgetReached extends Error {
|
|
22
|
+
}
|
|
23
|
+
/** Jev failed or didn't answer twice: the caller may carry on without its answers. */
|
|
24
|
+
export class Unavailable extends Error {
|
|
25
|
+
}
|
|
26
|
+
/** The key from the environment, else from a TYPESAFE_API_KEY= line in ./.env; undefined when there is none. */
|
|
27
|
+
export function apiKey() {
|
|
28
|
+
if (process.env.TYPESAFE_API_KEY)
|
|
29
|
+
return process.env.TYPESAFE_API_KEY;
|
|
30
|
+
const line = existsSync('.env') ? readFileSync('.env', 'utf8').split('\n').find((l) => l.startsWith('TYPESAFE_API_KEY=')) : undefined;
|
|
31
|
+
return line?.slice('TYPESAFE_API_KEY='.length).trim().replace(/^["']|["']$/g, '') || undefined;
|
|
32
|
+
}
|
|
33
|
+
/** Why Jev isn't asked in this run ('JEV=off', no key), or '' when it is. */
|
|
34
|
+
export const whyOff = () => (process.env.JEV === 'off' ? 'JEV=off' : client || apiKey() ? '' : 'no TYPESAFE_API_KEY');
|
|
35
|
+
let opts = { budget: 1, headers: {} };
|
|
36
|
+
let client = null;
|
|
37
|
+
let tokens = 0, calls = 0, cached = 0, ms = 0;
|
|
38
|
+
export const payloads = [];
|
|
39
|
+
const memo = new Map();
|
|
40
|
+
/** Starts a run: its budget and headers, counters and memo cleared. A self-check passes a fake client; nothing then reaches the network. */
|
|
41
|
+
export function setup(jev, fake) {
|
|
42
|
+
opts = jev;
|
|
43
|
+
client = fake ?? null;
|
|
44
|
+
tokens = calls = cached = ms = 0;
|
|
45
|
+
payloads.length = 0;
|
|
46
|
+
memo.clear();
|
|
47
|
+
}
|
|
48
|
+
/** One Jev request. `images` are the files behind the images in `state`: they key the memo and stand in for the bytes in the log. */
|
|
49
|
+
export async function ask(label, state, questions, images, model) {
|
|
50
|
+
const shown = JSON.parse(JSON.stringify(state)); // the SDK writes each image as a short "<image:…>" name here, never its bytes
|
|
51
|
+
const hash = createHash('sha256').update(JSON.stringify([model, shown, questions]));
|
|
52
|
+
for (const f of images)
|
|
53
|
+
hash.update(readFileSync(f));
|
|
54
|
+
const key = hash.digest('hex');
|
|
55
|
+
if (memo.has(key)) {
|
|
56
|
+
cached++;
|
|
57
|
+
payloads.push({ label, cached: true, images });
|
|
58
|
+
return memo.get(key);
|
|
59
|
+
}
|
|
60
|
+
if (spent() >= opts.budget)
|
|
61
|
+
throw new BudgetReached(`Jev budget of $${opts.budget} reached (raise jev.budget or JEV_BUDGET)`);
|
|
62
|
+
if (!client) {
|
|
63
|
+
const key = apiKey();
|
|
64
|
+
if (!key)
|
|
65
|
+
throw new Error('TYPESAFE_API_KEY is not set (environment, or a TYPESAFE_API_KEY= line in .env here).');
|
|
66
|
+
client = new TypeSafeClient({ apiKey: key, defaultHeaders: { ...IMAGES, ...opts.headers } });
|
|
67
|
+
}
|
|
68
|
+
const t0 = Date.now();
|
|
69
|
+
// A request that hangs or fails is tried once more; a second failure is the caller's to report.
|
|
70
|
+
const once = () => {
|
|
71
|
+
let timer;
|
|
72
|
+
const cap = new Promise((_, no) => { timer = setTimeout(() => no(new Error('Jev did not answer within 120 s')), 120_000); });
|
|
73
|
+
return Promise.race([client.systemOne({ state, questions, ...(model ? { model } : {}) }), cap]).finally(() => clearTimeout(timer));
|
|
74
|
+
};
|
|
75
|
+
const r = await once().catch(async () => { await new Promise((done) => setTimeout(done, 2000)); return once(); })
|
|
76
|
+
.catch((e) => { throw new Unavailable(String(e?.message ?? e)); });
|
|
77
|
+
const took = Date.now() - t0;
|
|
78
|
+
calls++;
|
|
79
|
+
ms += took;
|
|
80
|
+
tokens += r.usage.input_tokens ?? 0;
|
|
81
|
+
payloads.push({ label, model: model ?? 'default', ms: took, input_tokens: r.usage.input_tokens, state: shown, images, questions });
|
|
82
|
+
memo.set(key, r.answers);
|
|
83
|
+
return r.answers;
|
|
84
|
+
}
|
|
85
|
+
export const img = (file) => image(readFileSync(file));
|
|
86
|
+
export const spent = () => tokens * USD_PER_TOKEN;
|
|
87
|
+
export const usage = () => ({ tokens, usd: Math.round(spent() * 10000) / 10000, budget: opts.budget, calls, cached, avgMs: calls ? Math.round(ms / calls) : 0 });
|
|
88
|
+
/** Every request of the run, as sent (images as file paths; the key and headers are not part of it). */
|
|
89
|
+
export const savePayloads = (dir) => writeFileSync(`${dir}/payloads.json`, JSON.stringify(payloads, null, 2));
|