tslaws 0.3.1 → 0.3.2

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.
@@ -47,3 +47,16 @@ export { reactAdapter } from './adapters/react.ts';
47
47
  export type { ReactFunctions, ReactRootLike } from './adapters/react.ts';
48
48
  export { angularAdapter } from './adapters/angular.ts';
49
49
  export type { AngularAppRefLike, AngularComponentRefLike, AngularFunctions } from './adapters/angular.ts';
50
+ export interface Timing {
51
+ runs: number;
52
+ min: number;
53
+ median: number;
54
+ p95: number;
55
+ max: number;
56
+ }
57
+ /** Times `work` (sync or async) over `runs` runs after a warm-up, in milliseconds as the browser clock reads them. */
58
+ export declare function measure(work: () => unknown, runs?: number): Promise<Timing>;
59
+ /** True when `work` takes at most `budgetMs` at the median, so a law can `return await fast(() => click(add), 50)`. */
60
+ export declare function fast(work: () => unknown, budgetMs: number, runs?: number): Promise<boolean>;
61
+ /** Milliseconds the main thread was blocked by long tasks (over 50 ms) while `work` ran; 0 where the browser has no such API. */
62
+ export declare function blocking(work: () => unknown): Promise<number>;
@@ -92,3 +92,48 @@ export { domAdapter } from "./adapters/dom.js";
92
92
  export { elementAdapter } from "./adapters/element.js";
93
93
  export { reactAdapter } from "./adapters/react.js";
94
94
  export { angularAdapter } from "./adapters/angular.js";
95
+ /** Times `work` (sync or async) over `runs` runs after a warm-up, in milliseconds as the browser clock reads them. */
96
+ export async function measure(work, runs = 7) {
97
+ await settle();
98
+ await work();
99
+ const times = [];
100
+ for (let i = 0; i < runs; i++) {
101
+ const start = performance.now();
102
+ await work();
103
+ await settle(1);
104
+ times.push(performance.now() - start);
105
+ }
106
+ times.sort((a, b) => a - b);
107
+ const at = (q) => times[Math.min(times.length - 1, Math.floor(q * times.length))] ?? 0;
108
+ return { runs, min: times[0] ?? 0, median: at(0.5), p95: at(0.95), max: times[times.length - 1] ?? 0 };
109
+ }
110
+ /** True when `work` takes at most `budgetMs` at the median, so a law can `return await fast(() => click(add), 50)`. */
111
+ export async function fast(work, budgetMs, runs = 7) {
112
+ return (await measure(work, runs)).median <= budgetMs;
113
+ }
114
+ /** Milliseconds the main thread was blocked by long tasks (over 50 ms) while `work` ran; 0 where the browser has no such API. */
115
+ export async function blocking(work) {
116
+ let blocked = 0;
117
+ const add = (entries) => {
118
+ for (const entry of entries)
119
+ blocked += Math.max(0, entry.duration - 50);
120
+ };
121
+ let observer;
122
+ try {
123
+ observer = new PerformanceObserver((list) => add(list.getEntries()));
124
+ observer.observe({ type: 'longtask' });
125
+ }
126
+ catch {
127
+ observer = undefined;
128
+ }
129
+ // A task of its own, so that `work` is measured as a task and not as part of the caller's.
130
+ await new Promise((done, fail) => setTimeout(() => {
131
+ Promise.resolve(work()).then(() => done(), fail);
132
+ }, 0));
133
+ await settle();
134
+ // takeRecords flushes the entries the browser has queued for the observer, so there is nothing to wait for.
135
+ if (observer !== undefined)
136
+ add(observer.takeRecords());
137
+ observer?.disconnect();
138
+ return blocked;
139
+ }
package/dist/bundled.d.ts CHANGED
@@ -11,5 +11,7 @@ export declare const executableName: (os?: string) => string;
11
11
  export declare function hostPlatform(): Platform | undefined;
12
12
  /** The compiler installed as an optional dependency of tslaws, when there is one for this machine. */
13
13
  export declare function bundledCompiler(): string | undefined;
14
+ /** The compiler built in a checkout of the tsc-laws repository (packages/tsc-ts/dist), found by walking up from `from`. */
15
+ export declare function checkoutCompiler(from: string): string | undefined;
14
16
  /** The version of this package, for messages. */
15
17
  export declare function ownVersion(): string;
package/dist/bundled.js CHANGED
@@ -44,6 +44,17 @@ export function bundledCompiler() {
44
44
  return undefined;
45
45
  }
46
46
  }
47
+ /** The compiler built in a checkout of the tsc-laws repository (packages/tsc-ts/dist), found by walking up from `from`. */
48
+ export function checkoutCompiler(from) {
49
+ const name = process.platform === 'win32' ? 'tsc.exe' : 'tsc';
50
+ for (let dir = from;; dir = dirname(dir)) {
51
+ const candidate = join(dir, 'packages', 'tsc-ts', 'dist', name);
52
+ if (existsSync(candidate))
53
+ return candidate;
54
+ if (dirname(dir) === dir)
55
+ return undefined;
56
+ }
57
+ }
47
58
  /** The version of this package, for messages. */
48
59
  export function ownVersion() {
49
60
  try {
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@ import { createInterface } from 'node:readline/promises';
2
2
  import { readdirSync, statSync, watch } from 'node:fs';
3
3
  import { join, relative, resolve, sep } from 'node:path';
4
4
  import { resolveEngine } from "./browser.js";
5
- import { bundledCompiler } from "./bundled.js";
5
+ import { bundledCompiler, checkoutCompiler } from "./bundled.js";
6
6
  import { check, exemptionsOf } from "./check.js";
7
7
  import { readManifest } from "./compile.js";
8
8
  import { hintFor } from "./hints.js";
@@ -18,7 +18,7 @@ import { serveUi } from "./ui.js";
18
18
  import { writeLock } from "./lock.js";
19
19
  const usage = `tslaws init [--force] scaffold tslaws.json, .gitignore, AGENTS.md, Claude Code hooks and a starter law (never writes the lock)
20
20
  tslaws check [files...] [--reporter text|json|junit|github] [--json] [--summary] [--watch] [--runs N] [--seed N] [--no-prove] [--no-regressions] [--bound N] [--proof-timeout MS] [--property-timeout MS] [--proposed] [--compiler PATH] [--browser chromium|firefox|webkit]
21
- tslaws ui [files...] [--port N] [--no-open] open a dashboard of the laws in a browser: tree, filters, search, source, live reruns on save
21
+ tslaws ui [files...] [--port N] [--no-open] [--tab] open a dashboard of the laws in its own desktop window (--tab: a browser tab): tree, filters, search, source, live reruns on save
22
22
  tslaws mutate [files...] [--max N] [--seed N] [--runs N] [--bound N] [--proof-timeout MS] [--property-timeout MS] [--browser ENGINE] [--json] mutation-test the laws: mutate covered code, report mutants no law kills
23
23
  tslaws regressions [list|clear] show or delete the stored counterexamples (.tslaws/regressions); check replays them first, --no-regressions skips them
24
24
  tslaws accept [files...] record the current laws in tsc-laws.lock (people only: needs a terminal)
@@ -151,7 +151,7 @@ function options(cwd, flags, chosen) {
151
151
  cwd,
152
152
  runs: settings.runs,
153
153
  seed: flags.has('seed') ? Number(flags.get('seed')) : undefined,
154
- compiler: String(flags.get('compiler') ?? process.env.TSC_LAWS_BIN ?? bundledCompiler() ?? 'tsc-laws'),
154
+ compiler: String(flags.get('compiler') ?? process.env.TSC_LAWS_BIN ?? bundledCompiler() ?? checkoutCompiler(cwd) ?? 'tsc-laws'),
155
155
  lockFile: join(cwd, 'tsc-laws.lock'),
156
156
  noProve: flags.has('no-prove'),
157
157
  noRegressions: flags.has('no-regressions'),
@@ -350,6 +350,7 @@ export async function main(args) {
350
350
  cwd,
351
351
  port: Number(flags.get('port') ?? 51205),
352
352
  open: !flags.has('no-open'),
353
+ appWindow: !flags.has('tab'),
353
354
  // A watcher sees a browser page only if it stays as the law left it for a moment.
354
355
  run: (only, onEvent, laws) => check({ ...options(cwd, flags, only ?? chosen), only: laws, onEvent, browserPauseMs: 120 }, !flags.has('proposed')),
355
356
  log: (line) => process.stdout.write(`${line}\n`),
package/dist/compile.d.ts CHANGED
@@ -5,7 +5,6 @@ export interface BuildResult {
5
5
  diagnostics: string;
6
6
  ok: boolean;
7
7
  }
8
- /** Lists the laws of `files` with the problems that stop them running. */
9
8
  export declare function readManifest(compiler: string, files: string[], cwd: string): ManifestLaw[];
10
9
  /**
11
10
  * The compiler flags for the `compilerOptions` of tslaws.json. Only the supported keys pass; anything else is an
package/dist/compile.js CHANGED
@@ -36,6 +36,12 @@ function compilerEnv(cwd, compiler) {
36
36
  }
37
37
  }
38
38
  /** Lists the laws of `files` with the problems that stop them running. */
39
+ /** Says what to do when the compiler cannot start, in particular when none was found at all. */
40
+ function cannotRun(compiler, error) {
41
+ if (error.code === 'ENOENT')
42
+ return `no tsc-laws compiler found (${compiler}): install the tslaws-compiler package for this platform, or set TSC_LAWS_BIN / --compiler to the compiler executable`;
43
+ return `cannot run ${compiler}: ${error.message}`;
44
+ }
39
45
  export function readManifest(compiler, files, cwd) {
40
46
  const run = launch(compiler, ['--laws-manifest', ...files], {
41
47
  cwd,
@@ -44,7 +50,7 @@ export function readManifest(compiler, files, cwd) {
44
50
  env: compilerEnv(cwd, compiler),
45
51
  });
46
52
  if (run.error !== undefined)
47
- throw new Error(`cannot run ${compiler}: ${run.error.message}`);
53
+ throw new Error(cannotRun(compiler, run.error));
48
54
  const text = (run.stdout ?? '').trim();
49
55
  if (text === '')
50
56
  throw new Error(`${compiler} --laws-manifest printed nothing: ${run.stderr ?? ''}`);
@@ -131,6 +137,6 @@ export function build(compiler, files, cwd) {
131
137
  `${run.stdout ?? ''}${run.stderr ?? ''}`.trim() === ''; attempt += 1)
132
138
  run = launch(compiler, args, { cwd, encoding: 'utf8', maxBuffer: 64 << 20, env: compilerEnv(cwd, compiler) });
133
139
  if (run.error !== undefined)
134
- throw new Error(`cannot run ${compiler}: ${run.error.message}`);
140
+ throw new Error(cannotRun(compiler, run.error));
135
141
  return { outDir, diagnostics: `${run.stdout ?? ''}${run.stderr ?? ''}`.trim(), ok: run.status === 0 };
136
142
  }
package/dist/e2e.js CHANGED
@@ -208,8 +208,21 @@ async function startServer(server, cwd) {
208
208
  throw error;
209
209
  }
210
210
  }
211
- /** Runs `law` once in a fresh context; `keep` leaves the page open for a photograph. */
211
+ /** A browser that died under the machine, as opposed to a law that failed. */
212
+ const crashed = /Target (?:page, context or browser has been closed|crashed)|Page crashed|browser has been closed/;
213
+ /** Runs `law` once in a fresh context; `keep` leaves the page open for a photograph. A crashed browser tab is tried again, twice at most. */
212
214
  async function runOnce(law, args, contextOf, baseURL, options, track, keep) {
215
+ for (let attempt = 0;; attempt += 1) {
216
+ try {
217
+ return await runAttempt(law, args, contextOf, baseURL, options, track, keep);
218
+ }
219
+ catch (error) {
220
+ if (attempt >= 2 || !crashed.test(error instanceof Error ? error.message : String(error)))
221
+ throw error;
222
+ }
223
+ }
224
+ }
225
+ async function runAttempt(law, args, contextOf, baseURL, options, track, keep) {
213
226
  const context = await contextOf();
214
227
  let closing = true;
215
228
  try {
package/dist/e2eApi.d.ts CHANGED
@@ -46,3 +46,35 @@ export declare function a11y(target?: Page, options?: A11yOptions): Promise<{
46
46
  }>;
47
47
  /** True when the page has no accessibility violations, so a law can `return await accessible()`. */
48
48
  export declare function accessible(target?: Page, options?: A11yOptions): Promise<boolean>;
49
+ /** What the browser measured for the page: the numbers behind Core Web Vitals, plus size. Times are milliseconds. */
50
+ export interface Vitals {
51
+ /** Time to first contentful paint. */
52
+ fcp: number | null;
53
+ /** Largest contentful paint (Chromium). */
54
+ lcp: number | null;
55
+ /** Cumulative layout shift, unitless (Chromium). */
56
+ cls: number;
57
+ /** Time the main thread was blocked by long tasks beyond 50 ms each (Chromium). */
58
+ blocking: number;
59
+ /** DOMContentLoaded and load, from navigation start. */
60
+ domContentLoaded: number | null;
61
+ load: number | null;
62
+ /** Elements in the document. */
63
+ domNodes: number;
64
+ /** Bytes transferred for the page and everything it loaded. */
65
+ bytes: number;
66
+ }
67
+ export type SpeedBudget = Partial<Record<keyof Vitals, number>>;
68
+ /** Measures the page as it stands: paint, layout shift, blocking time, load and size. Call it after `open()` and `settle()`. */
69
+ export declare function vitals(target?: Page): Promise<Vitals>;
70
+ /**
71
+ * Checks the page against a budget, for example `{ lcp: 2500, cls: 0.1, blocking: 200 }`. `violations` names each measure over its
72
+ * budget, so an agent sees what to fix; a measure the browser cannot report counts as over.
73
+ */
74
+ export declare function speed(budget: SpeedBudget, target?: Page): Promise<{
75
+ vitals: Vitals;
76
+ violations: string[];
77
+ ok: boolean;
78
+ }>;
79
+ /** True when the page is within `budget`, so a law can `return await fast({ lcp: 2500 })`. */
80
+ export declare function fast(budget: SpeedBudget, target?: Page): Promise<boolean>;
package/dist/e2eApi.js CHANGED
@@ -90,3 +90,51 @@ function axeConfig(options) {
90
90
  export async function accessible(target, options) {
91
91
  return (await a11y(target, options)).ok;
92
92
  }
93
+ const vitalsScript = `new Promise((done) => {
94
+ const out = { fcp: null, lcp: null, cls: 0, blocking: 0 };
95
+ const watch = (type, onEntry) => {
96
+ try {
97
+ new PerformanceObserver((list) => list.getEntries().forEach(onEntry)).observe({ type, buffered: true });
98
+ } catch {}
99
+ };
100
+ watch('paint', (e) => { if (e.name === 'first-contentful-paint') out.fcp = e.startTime; });
101
+ watch('largest-contentful-paint', (e) => { out.lcp = e.startTime; });
102
+ watch('layout-shift', (e) => { if (!e.hadRecentInput) out.cls += e.value; });
103
+ watch('longtask', (e) => { out.blocking += Math.max(0, e.duration - 50); });
104
+ setTimeout(() => {
105
+ const nav = performance.getEntriesByType('navigation')[0];
106
+ const bytes = performance.getEntriesByType('resource').reduce((sum, r) => sum + (r.transferSize || 0), nav ? nav.transferSize || 0 : 0);
107
+ done({
108
+ ...out,
109
+ domContentLoaded: nav ? nav.domContentLoadedEventEnd : null,
110
+ load: nav && nav.loadEventEnd > 0 ? nav.loadEventEnd : null,
111
+ domNodes: document.getElementsByTagName('*').length,
112
+ bytes,
113
+ });
114
+ }, 250);
115
+ })`;
116
+ /** Measures the page as it stands: paint, layout shift, blocking time, load and size. Call it after `open()` and `settle()`. */
117
+ export async function vitals(target) {
118
+ const used = target ?? current().page;
119
+ return (await used.evaluate(vitalsScript));
120
+ }
121
+ /**
122
+ * Checks the page against a budget, for example `{ lcp: 2500, cls: 0.1, blocking: 200 }`. `violations` names each measure over its
123
+ * budget, so an agent sees what to fix; a measure the browser cannot report counts as over.
124
+ */
125
+ export async function speed(budget, target) {
126
+ const measured = await vitals(target);
127
+ const violations = [];
128
+ for (const [name, limit] of Object.entries(budget)) {
129
+ const value = measured[name];
130
+ if (value === null)
131
+ violations.push(`${name}: not reported (budget ${limit})`);
132
+ else if (value > limit)
133
+ violations.push(`${name}: ${Math.round(value * 1000) / 1000} over budget ${limit}`);
134
+ }
135
+ return { vitals: measured, violations, ok: violations.length === 0 };
136
+ }
137
+ /** True when the page is within `budget`, so a law can `return await fast({ lcp: 2500 })`. */
138
+ export async function fast(budget, target) {
139
+ return (await speed(budget, target)).ok;
140
+ }
package/dist/ui.d.ts CHANGED
@@ -4,6 +4,8 @@ export interface UiOptions {
4
4
  cwd: string;
5
5
  port: number;
6
6
  open: boolean;
7
+ /** Open in its own chromeless window (Chrome, Edge or Chromium) rather than a tab, so it reads as a desktop app. */
8
+ appWindow?: boolean;
7
9
  /** Runs the check of the project, of just these law files, or (with `laws`, in one file) of just these laws. */
8
10
  run: (files: string[] | undefined, onEvent: (event: LawEvent) => void, laws?: string[]) => Promise<CheckReport>;
9
11
  log: (line: string) => void;
package/dist/ui.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // status filters and search, a detail pane (report, source, diagnostics), and live reruns when a file changes.
3
3
  // It listens on 127.0.0.1 only and offers no way to accept laws: that stays a person's act at a terminal.
4
4
  import { spawn } from 'node:child_process';
5
- import { readFileSync, watch } from 'node:fs';
5
+ import { existsSync, readFileSync, watch } from 'node:fs';
6
6
  import { createServer } from 'node:http';
7
7
  import { basename, join, resolve, sep } from 'node:path';
8
8
  import { hintFor } from "./hints.js";
@@ -29,7 +29,34 @@ function sourceOf(cwd, file) {
29
29
  return undefined;
30
30
  }
31
31
  }
32
- function openInBrowser(url) {
32
+ /** A Chromium-family browser, which can show the page as an app window. */
33
+ function appBrowser() {
34
+ const env = process.env;
35
+ const candidates = process.platform === 'win32'
36
+ ? [env['ProgramFiles(x86)'], env['ProgramFiles'], env['LOCALAPPDATA']].flatMap((base) => base === undefined
37
+ ? []
38
+ : [join(base, 'Microsoft/Edge/Application/msedge.exe'), join(base, 'Google/Chrome/Application/chrome.exe')])
39
+ : process.platform === 'darwin'
40
+ ? [
41
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
42
+ '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
43
+ ]
44
+ : ['/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/usr/bin/microsoft-edge'];
45
+ return candidates.find((path) => existsSync(path));
46
+ }
47
+ function openInBrowser(url, appWindow) {
48
+ const browser = appWindow ? appBrowser() : undefined;
49
+ if (browser !== undefined) {
50
+ try {
51
+ spawn(browser, [`--app=${url}`, '--window-size=1360,860', '--no-first-run'], { stdio: 'ignore', detached: true })
52
+ .on('error', () => undefined)
53
+ .unref();
54
+ return;
55
+ }
56
+ catch {
57
+ // Falls back to the default browser.
58
+ }
59
+ }
33
60
  const [command, args] = process.platform === 'win32'
34
61
  ? ['cmd', ['/c', 'start', '', url]]
35
62
  : process.platform === 'darwin'
@@ -276,7 +303,7 @@ export async function serveUi(options) {
276
303
  const url = `http://127.0.0.1:${port}/`;
277
304
  options.log(`tslaws ui: ${url} (Ctrl+C exits)`);
278
305
  if (options.open)
279
- openInBrowser(url);
306
+ openInBrowser(url, options.appWindow ?? false);
280
307
  let timer;
281
308
  const watcher = watch(cwd, { recursive: true }, (_event, filename) => {
282
309
  const name = filename === null ? null : String(filename);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tslaws",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "Runs and checks `law` declarations compiled by tsc-laws: property tests, SMT proofs, tamper lock.",
5
5
  "bin": {
6
6
  "tslaws": "bin/tslaws.js"
@@ -69,11 +69,11 @@
69
69
  }
70
70
  },
71
71
  "optionalDependencies": {
72
- "tslaws-compiler-darwin-arm64": "0.3.1",
73
- "tslaws-compiler-darwin-x64": "0.3.1",
74
- "tslaws-compiler-linux-arm64-gnu": "0.3.1",
75
- "tslaws-compiler-linux-x64-gnu": "0.3.1",
76
- "tslaws-compiler-win32-x64-msvc": "0.3.1"
72
+ "tslaws-compiler-darwin-arm64": "0.3.2",
73
+ "tslaws-compiler-darwin-x64": "0.3.2",
74
+ "tslaws-compiler-linux-arm64-gnu": "0.3.2",
75
+ "tslaws-compiler-linux-x64-gnu": "0.3.2",
76
+ "tslaws-compiler-win32-x64-msvc": "0.3.2"
77
77
  },
78
78
  "publishConfig": {
79
79
  "access": "public"