tslaws 0.0.0-stage → 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.
Files changed (74) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +215 -2
  3. package/bin/tslaws.js +5 -0
  4. package/dist/adapters/angular.d.ts +42 -0
  5. package/dist/adapters/angular.js +40 -0
  6. package/dist/adapters/dom.d.ts +5 -0
  7. package/dist/adapters/dom.js +17 -0
  8. package/dist/adapters/element.d.ts +10 -0
  9. package/dist/adapters/element.js +28 -0
  10. package/dist/adapters/react.d.ts +24 -0
  11. package/dist/adapters/react.js +15 -0
  12. package/dist/api.d.ts +59 -0
  13. package/dist/api.js +103 -0
  14. package/dist/browser.d.ts +24 -0
  15. package/dist/browser.js +252 -0
  16. package/dist/browserApi.d.ts +62 -0
  17. package/dist/browserApi.js +139 -0
  18. package/dist/bundled.d.ts +17 -0
  19. package/dist/bundled.js +67 -0
  20. package/dist/check.d.ts +12 -0
  21. package/dist/check.js +269 -0
  22. package/dist/cli.d.ts +1 -0
  23. package/dist/cli.js +360 -0
  24. package/dist/compile.d.ts +15 -0
  25. package/dist/compile.js +142 -0
  26. package/dist/component.d.ts +37 -0
  27. package/dist/component.js +99 -0
  28. package/dist/coverage.d.ts +40 -0
  29. package/dist/coverage.js +237 -0
  30. package/dist/e2e.d.ts +46 -0
  31. package/dist/e2e.js +322 -0
  32. package/dist/e2eApi.d.ts +80 -0
  33. package/dist/e2eApi.js +140 -0
  34. package/dist/generators.d.ts +18 -0
  35. package/dist/generators.js +184 -0
  36. package/dist/hints.d.ts +3 -0
  37. package/dist/hints.js +37 -0
  38. package/dist/init.d.ts +23 -0
  39. package/dist/init.js +139 -0
  40. package/dist/lock.d.ts +16 -0
  41. package/dist/lock.js +40 -0
  42. package/dist/mcp.d.ts +30 -0
  43. package/dist/mcp.js +301 -0
  44. package/dist/mutate.d.ts +54 -0
  45. package/dist/mutate.js +293 -0
  46. package/dist/promote.d.ts +38 -0
  47. package/dist/promote.js +217 -0
  48. package/dist/property.d.ts +37 -0
  49. package/dist/property.js +172 -0
  50. package/dist/propertyWorker.d.ts +1 -0
  51. package/dist/propertyWorker.js +24 -0
  52. package/dist/queries.d.ts +37 -0
  53. package/dist/queries.js +297 -0
  54. package/dist/regressions.d.ts +31 -0
  55. package/dist/regressions.js +153 -0
  56. package/dist/reporters.d.ts +22 -0
  57. package/dist/reporters.js +160 -0
  58. package/dist/settings.d.ts +16 -0
  59. package/dist/settings.js +15 -0
  60. package/dist/smt.d.ts +33 -0
  61. package/dist/smt.js +396 -0
  62. package/dist/symbolic.d.ts +200 -0
  63. package/dist/symbolic.js +1727 -0
  64. package/dist/types.d.ts +77 -0
  65. package/dist/types.js +1 -0
  66. package/dist/ui.d.ts +16 -0
  67. package/dist/ui.js +326 -0
  68. package/dist/uiPage.d.ts +1 -0
  69. package/dist/uiPage.js +4 -0
  70. package/hooks/AGENTS.snippet.md +10 -0
  71. package/hooks/claude-hook.mjs +35 -0
  72. package/hooks/claude-settings.example.json +8 -0
  73. package/package.json +85 -4
  74. package/ui/index.html +1132 -0
@@ -0,0 +1,80 @@
1
+ import type { BrowserContext, Locator, Page, Route } from 'playwright-core';
2
+ export type { BrowserContext, Locator, Page, Route };
3
+ /** What the runner provides to a law while it runs one generated input. */
4
+ export interface E2eState {
5
+ context: BrowserContext;
6
+ page: Page;
7
+ baseURL: string;
8
+ /** The project directory, where axe-core is looked up. */
9
+ cwd: string;
10
+ /** Called with each page the law opens, so the runner can photograph the newest. */
11
+ onPage?: (page: Page) => void;
12
+ }
13
+ /** For the runner: runs `fn` with `state` as the current run. */
14
+ export declare function withE2e<T>(state: E2eState, fn: () => Promise<T> | T): Promise<T> | T;
15
+ /** The Playwright page of the current run: a fresh browser context and page for every generated input. */
16
+ export declare function page(): Page;
17
+ /** The browser context of the current run. Cookies and storage are shared by its tabs and gone after the run. */
18
+ export declare function context(): BrowserContext;
19
+ /** The address of the app under test: `e2e.baseURL` of tslaws.json. */
20
+ export declare function baseURL(): string;
21
+ /** Opens `path` (relative to the base URL) and waits for the page to load. */
22
+ export declare function open(path?: string): Promise<Page>;
23
+ /** Opens a second tab in the same context (same cookies and storage). */
24
+ export declare function newPage(): Promise<Page>;
25
+ /** Answers requests matching `urlPattern` yourself, for network mocking. Lasts until the run ends. */
26
+ export declare function route(urlPattern: string | RegExp | ((url: URL) => boolean), handler: (route: Route) => Promise<void> | void): Promise<void>;
27
+ /** Waits until the network is idle and two animation frames have run, so the page has caught up. */
28
+ export declare function settle(target?: Page): Promise<void>;
29
+ export interface A11yViolation {
30
+ id: string;
31
+ impact: string | null;
32
+ help: string;
33
+ /** Outer HTML of each offending element, trimmed to 200 characters. */
34
+ nodes: string[];
35
+ }
36
+ export interface A11yOptions {
37
+ /** Run only these axe rule ids. */
38
+ rules?: string[];
39
+ /** Skip these axe rule ids. */
40
+ ignore?: string[];
41
+ }
42
+ /** Audits the page with axe-core, which it looks up in the project (`npm i -D axe-core`). */
43
+ export declare function a11y(target?: Page, options?: A11yOptions): Promise<{
44
+ violations: A11yViolation[];
45
+ ok: boolean;
46
+ }>;
47
+ /** True when the page has no accessibility violations, so a law can `return await accessible()`. */
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 ADDED
@@ -0,0 +1,140 @@
1
+ // Helpers for end-to-end laws (`*.e2e.laws.ts`). The law runs in Node and drives a whole running app from outside,
2
+ // through a real browser, with a Playwright `Page`. The runner gives every generated input a fresh browser context
3
+ // and page; the helpers below find them through async context, so a law needs no argument for them.
4
+ import { AsyncLocalStorage } from 'node:async_hooks';
5
+ import { createRequire } from 'node:module';
6
+ import { join } from 'node:path';
7
+ // The runner and the law may load this module through different paths (an ESM import and a CommonJS `require`), so
8
+ // the storage lives on the global object and both see the same one.
9
+ const key = Symbol.for('tslaws.e2e.state');
10
+ function storage() {
11
+ const holder = globalThis;
12
+ return (holder[key] ??= new AsyncLocalStorage());
13
+ }
14
+ /** For the runner: runs `fn` with `state` as the current run. */
15
+ export function withE2e(state, fn) {
16
+ return storage().run(state, fn);
17
+ }
18
+ function current() {
19
+ const state = storage().getStore();
20
+ if (state === undefined)
21
+ throw new Error('tslaws/e2e helpers only work inside an end-to-end law (*.e2e.laws.ts)');
22
+ return state;
23
+ }
24
+ /** The Playwright page of the current run: a fresh browser context and page for every generated input. */
25
+ export function page() {
26
+ return current().page;
27
+ }
28
+ /** The browser context of the current run. Cookies and storage are shared by its tabs and gone after the run. */
29
+ export function context() {
30
+ return current().context;
31
+ }
32
+ /** The address of the app under test: `e2e.baseURL` of tslaws.json. */
33
+ export function baseURL() {
34
+ return current().baseURL;
35
+ }
36
+ /** Opens `path` (relative to the base URL) and waits for the page to load. */
37
+ export async function open(path = '/') {
38
+ const state = current();
39
+ await state.page.goto(new URL(path, state.baseURL).toString(), { waitUntil: 'load' });
40
+ return state.page;
41
+ }
42
+ /** Opens a second tab in the same context (same cookies and storage). */
43
+ export async function newPage() {
44
+ const state = current();
45
+ const created = await state.context.newPage();
46
+ state.onPage?.(created);
47
+ return created;
48
+ }
49
+ /** Answers requests matching `urlPattern` yourself, for network mocking. Lasts until the run ends. */
50
+ export async function route(urlPattern, handler) {
51
+ await current().context.route(urlPattern, handler);
52
+ }
53
+ /** Waits until the network is idle and two animation frames have run, so the page has caught up. */
54
+ export async function settle(target) {
55
+ const used = target ?? current().page;
56
+ await used.waitForLoadState('networkidle');
57
+ // Strings, not functions: this file is compiled without the DOM types.
58
+ await used.evaluate('new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(() => done())))');
59
+ }
60
+ /** Audits the page with axe-core, which it looks up in the project (`npm i -D axe-core`). */
61
+ export async function a11y(target, options = {}) {
62
+ const state = current();
63
+ const used = target ?? state.page;
64
+ let axePath;
65
+ try {
66
+ axePath = createRequire(join(state.cwd, 'package.json')).resolve('axe-core/axe.min.js');
67
+ }
68
+ catch {
69
+ throw new Error('accessible() needs axe-core: npm i -D axe-core');
70
+ }
71
+ await used.addScriptTag({ path: axePath });
72
+ const results = (await used.evaluate(`axe.run(document, ${JSON.stringify(axeConfig(options))})`));
73
+ const violations = results.violations.map((v) => ({
74
+ id: v.id,
75
+ impact: v.impact ?? null,
76
+ help: v.help,
77
+ nodes: v.nodes.map((n) => (n.html.length > 200 ? `${n.html.slice(0, 197)}...` : n.html)),
78
+ }));
79
+ return { violations, ok: violations.length === 0 };
80
+ }
81
+ function axeConfig(options) {
82
+ const config = {};
83
+ if (options.rules !== undefined)
84
+ config.runOnly = { type: 'rule', values: options.rules };
85
+ if (options.ignore !== undefined && options.ignore.length > 0)
86
+ config.rules = Object.fromEntries(options.ignore.map((id) => [id, { enabled: false }]));
87
+ return config;
88
+ }
89
+ /** True when the page has no accessibility violations, so a law can `return await accessible()`. */
90
+ export async function accessible(target, options) {
91
+ return (await a11y(target, options)).ok;
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
+ }
@@ -0,0 +1,18 @@
1
+ import * as fc from 'fast-check';
2
+ import ts from 'typescript';
3
+ export declare class UnsupportedType extends Error {
4
+ }
5
+ /** Marks a generated function on the wire: browser laws receive their arguments as structured data. */
6
+ export declare const wireKey = "$tslawsFn";
7
+ /** Replaces generated functions inside arguments with a structured-clone-safe marker `{ $tslawsFn: samples }`. */
8
+ export declare function toWire(value: unknown): unknown;
9
+ export declare class GeneratorFactory {
10
+ private readonly checker;
11
+ private readonly active;
12
+ constructor(checker: ts.TypeChecker);
13
+ of(type: ts.Type, depth?: number): fc.Arbitrary<unknown>;
14
+ private registered;
15
+ private union;
16
+ private template;
17
+ private object;
18
+ }
@@ -0,0 +1,184 @@
1
+ // Derives fast-check generators from the declared parameter types of laws, read from the declaration
2
+ // files the compiler emitted. Full TypeScript types map: primitives, literals, unions, enums, arrays,
3
+ // tuples, object types, index signatures, type parameters (via their constraint) and registered names.
4
+ import * as fc from 'fast-check';
5
+ import ts from 'typescript';
6
+ import { arbitraryRegistry } from "./api.js";
7
+ export class UnsupportedType extends Error {
8
+ }
9
+ const numbers = fc.oneof({ weight: 4, arbitrary: fc.integer({ min: -8, max: 8 }) }, { weight: 3, arbitrary: fc.integer({ min: -1000, max: 1000 }) }, { weight: 1, arbitrary: fc.integer() }, { weight: 2, arbitrary: fc.double({ noNaN: true, noDefaultInfinity: true }) });
10
+ // `int` from 'tslaws': whole numbers, biased to small ones.
11
+ arbitraryRegistry().set('int', fc.oneof({ weight: 4, arbitrary: fc.integer({ min: -8, max: 8 }) }, { weight: 3, arbitrary: fc.integer({ min: -1000, max: 1000 }) }, { weight: 1, arbitrary: fc.integer({ min: -Number.MAX_SAFE_INTEGER, max: Number.MAX_SAFE_INTEGER }) }));
12
+ /** Marks a generated function on the wire: browser laws receive their arguments as structured data. */
13
+ export const wireKey = '$tslawsFn';
14
+ function pick(samples, args) {
15
+ let key = '';
16
+ try {
17
+ key = JSON.stringify(args) ?? '';
18
+ }
19
+ catch {
20
+ // Arguments that are not JSON (a node, a cycle) all share the first sample.
21
+ }
22
+ let h = 5381;
23
+ for (let i = 0; i < key.length; i++)
24
+ h = (Math.imul(h, 33) + key.charCodeAt(i)) | 0;
25
+ return samples[(h >>> 0) % samples.length];
26
+ }
27
+ /**
28
+ * A function of a type with one call signature: it returns one of a few values generated from the return type,
29
+ * chosen by its arguments (like `fc.func`: the same arguments give the same result, `void` gives `undefined`).
30
+ * `samples` rides along so a browser law can rebuild the function in the page.
31
+ */
32
+ function generatedFunction(samples) {
33
+ const fn = (...args) => pick(samples, args);
34
+ Object.defineProperty(fn, wireKey, { value: samples, enumerable: false });
35
+ Object.defineProperty(fn, 'toString', { value: () => `[generated function]`, enumerable: false });
36
+ return fn;
37
+ }
38
+ /** Replaces generated functions inside arguments with a structured-clone-safe marker `{ $tslawsFn: samples }`. */
39
+ export function toWire(value) {
40
+ if (typeof value === 'function') {
41
+ const samples = value[wireKey];
42
+ return { [wireKey]: Array.isArray(samples) ? samples : [undefined] };
43
+ }
44
+ if (Array.isArray(value))
45
+ return value.map(toWire);
46
+ if (value !== null && typeof value === 'object') {
47
+ const proto = Object.getPrototypeOf(value);
48
+ if (proto === Object.prototype || proto === null)
49
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, toWire(v)]));
50
+ }
51
+ return value;
52
+ }
53
+ export class GeneratorFactory {
54
+ checker;
55
+ active = new Set();
56
+ constructor(checker) {
57
+ this.checker = checker;
58
+ }
59
+ of(type, depth = 0) {
60
+ const named = this.registered(type);
61
+ if (named !== undefined)
62
+ return named;
63
+ const f = type.flags;
64
+ if (f & ts.TypeFlags.Any || f & ts.TypeFlags.Unknown)
65
+ return fc.anything();
66
+ if (f & ts.TypeFlags.Never)
67
+ throw new UnsupportedType('type never has no values');
68
+ if (f & ts.TypeFlags.Void || f & ts.TypeFlags.Undefined)
69
+ return fc.constant(undefined);
70
+ if (f & ts.TypeFlags.Null)
71
+ return fc.constant(null);
72
+ if (f & ts.TypeFlags.BooleanLiteral)
73
+ return fc.constant(this.checker.typeToString(type) === 'true');
74
+ if (f & ts.TypeFlags.Boolean)
75
+ return fc.boolean();
76
+ if (f & ts.TypeFlags.NumberLiteral)
77
+ return fc.constant(type.value);
78
+ if (f & ts.TypeFlags.StringLiteral)
79
+ return fc.constant(type.value);
80
+ if (f & ts.TypeFlags.BigIntLiteral) {
81
+ const v = type.value;
82
+ return fc.constant(BigInt(`${v.negative ? '-' : ''}${v.base10Value}`));
83
+ }
84
+ if (f & ts.TypeFlags.EnumLiteral && f & ts.TypeFlags.Union)
85
+ return this.union(type, depth);
86
+ if (f & ts.TypeFlags.Number)
87
+ return numbers;
88
+ if (f & ts.TypeFlags.String)
89
+ return fc.string({ maxLength: 24 });
90
+ if (f & ts.TypeFlags.BigInt)
91
+ return fc.bigInt();
92
+ if (f & ts.TypeFlags.ESSymbol)
93
+ return fc.string().map((s) => Symbol(s));
94
+ if (f & ts.TypeFlags.TemplateLiteral)
95
+ return this.template(type, depth);
96
+ if (f & ts.TypeFlags.TypeParameter) {
97
+ const constraint = this.checker.getBaseConstraintOfType(type);
98
+ if (constraint === undefined || constraint === type)
99
+ return fc.anything();
100
+ return this.of(constraint, depth);
101
+ }
102
+ if (f & ts.TypeFlags.Union)
103
+ return this.union(type, depth);
104
+ if (f & ts.TypeFlags.Intersection)
105
+ return this.object(type, depth);
106
+ if (f & ts.TypeFlags.Object)
107
+ return this.object(type, depth);
108
+ if (f & ts.TypeFlags.NonPrimitive)
109
+ return fc.object();
110
+ throw new UnsupportedType(`no generator for type ${this.checker.typeToString(type)}`);
111
+ }
112
+ registered(type) {
113
+ const symbol = type.aliasSymbol ?? type.getSymbol();
114
+ if (symbol === undefined)
115
+ return undefined;
116
+ return arbitraryRegistry().get(symbol.getName());
117
+ }
118
+ union(type, depth) {
119
+ const members = type.types.filter((t) => !(t.flags & ts.TypeFlags.Never));
120
+ return fc.oneof(...members.map((member) => this.of(member, depth)));
121
+ }
122
+ template(type, depth) {
123
+ const parts = [fc.constant(type.texts[0] ?? '')];
124
+ type.types.forEach((t, i) => {
125
+ parts.push(this.of(t, depth).map(String));
126
+ parts.push(fc.constant(type.texts[i + 1] ?? ''));
127
+ });
128
+ return fc.tuple(...parts).map((p) => p.join(''));
129
+ }
130
+ object(type, depth) {
131
+ const checker = this.checker;
132
+ if (this.active.has(type) || depth > 4)
133
+ return fc.constant(undefined);
134
+ const name = type.getSymbol()?.getName();
135
+ if (name === 'Date')
136
+ return fc.date({ noInvalidDate: true });
137
+ if (name === 'RegExp')
138
+ return fc.constant(/x/);
139
+ if (checker.isArrayType(type)) {
140
+ const element = checker.getTypeArguments(type)[0];
141
+ return fc.array(this.of(element, depth + 1), { maxLength: 8 });
142
+ }
143
+ if (checker.isTupleType(type)) {
144
+ const target = type.target;
145
+ const args = checker.getTypeArguments(type);
146
+ const required = args.slice(0, target.minLength).map((t) => this.of(t, depth + 1));
147
+ const optional = args.slice(target.minLength).map((t) => this.of(t, depth + 1));
148
+ return fc.tuple(...required).chain((head) => {
149
+ if (optional.length === 0)
150
+ return fc.constant(head);
151
+ return fc.tuple(...optional).map((tail) => [...head, ...tail]);
152
+ });
153
+ }
154
+ if (type.getCallSignatures().length > 0) {
155
+ const signature = type.getCallSignatures()[0];
156
+ const returns = this.of(checker.getReturnTypeOfSignature(signature), depth + 1);
157
+ return fc.array(returns, { minLength: 1, maxLength: 4 }).map(generatedFunction);
158
+ }
159
+ this.active.add(type);
160
+ try {
161
+ const model = {};
162
+ const required = [];
163
+ for (const property of checker.getPropertiesOfType(type)) {
164
+ const declaration = property.valueDeclaration ?? property.declarations?.[0];
165
+ if (declaration === undefined)
166
+ continue;
167
+ const propertyType = checker.getTypeOfSymbolAtLocation(property, declaration);
168
+ const optional = (property.flags & ts.SymbolFlags.Optional) !== 0;
169
+ const generator = this.of(optional ? checker.getNonNullableType(propertyType) : propertyType, depth + 1);
170
+ model[property.getName()] = generator;
171
+ if (!optional)
172
+ required.push(property.getName());
173
+ }
174
+ const index = checker.getIndexInfosOfType(type)[0];
175
+ if (index !== undefined && Object.keys(model).length === 0) {
176
+ return fc.dictionary(fc.string({ maxLength: 6 }), this.of(index.type, depth + 1), { maxKeys: 6 });
177
+ }
178
+ return fc.record(model, { requiredKeys: required });
179
+ }
180
+ finally {
181
+ this.active.delete(type);
182
+ }
183
+ }
184
+ }
@@ -0,0 +1,3 @@
1
+ import type { LawResult } from './types.ts';
2
+ /** The concrete next action for an agent that reads a result, or undefined when nothing needs doing. */
3
+ export declare function hintFor(result: LawResult): string | undefined;
package/dist/hints.js ADDED
@@ -0,0 +1,37 @@
1
+ /** The concrete next action for an agent that reads a result, or undefined when nothing needs doing. */
2
+ export function hintFor(result) {
3
+ switch (result.status) {
4
+ case 'proved':
5
+ return undefined;
6
+ case 'failed': {
7
+ const seed = result.seed !== undefined ? ` Reproduce with \`--seed ${result.seed}\`.` : '';
8
+ const example = result.counterexample !== undefined ? ` The counterexample is ${result.counterexample}.` : '';
9
+ return `The code breaks this law.${example} Fix the code, not the law, then rerun.${seed}`;
10
+ }
11
+ case 'open':
12
+ return ('Declared `proved` but no proof for every input was found' +
13
+ `${result.message !== undefined ? ` (${firstLine(result.message)})` : ''}. ` +
14
+ 'Make the code provable: use int or bigint for whole numbers, boolean, string and records with const/if/return and calls; ' +
15
+ 'remove the unsupported construct the message names; arrays and loops only reach `bounded`. ' +
16
+ 'If the law cannot be proved, ask a person to drop `proved` from it. Do not edit the law yourself.');
17
+ case 'bounded':
18
+ return (`Proved only within bounds${result.message !== undefined ? ` (${firstLine(result.message)})` : ''}: ` +
19
+ 'array length and loop iterations up to --bound (default 4), int values within +-2^26. ' +
20
+ 'Raise the array and loop bound with `--bound N`. Passing; no action needed unless a person wants a full proof.');
21
+ case 'tested':
22
+ return (`Only property-tested${result.runs !== undefined ? ` (${result.runs} runs)` : ''}, not proved: ` +
23
+ `the prover did not lower this law${result.method !== 'property' && result.method !== '' ? ` (${firstLine(result.method)})` : ''}. ` +
24
+ 'Passing; to get a proof, restrict the code to int/bigint/boolean/string and simple control flow. More inputs: `--runs N`.');
25
+ case 'uncovered':
26
+ return ('No law reaches this exported code. Ask a person for a law, or write a proposal in a `*.proposed.laws.ts` file ' +
27
+ 'and try it with `tslaws check --proposed`. Never edit a `*.laws.ts` file or add `@tslaws-exempt` yourself.');
28
+ case 'tampered':
29
+ return ('A law or coverage exemption differs from tsc-laws.lock. Never edit laws or the lock, and never run `tslaws accept`. ' +
30
+ 'Undo any change you made to laws or exemptions; if the change is intended, tell the person to review it and run `tslaws accept`.');
31
+ case 'error':
32
+ return `The law could not run${result.message !== undefined ? `: ${firstLine(result.message)}` : ''}. Fix the cause in the code. If the law itself is at fault (not exported, untyped parameter), do not edit it; tell the person.`;
33
+ }
34
+ }
35
+ function firstLine(text) {
36
+ return (text.split('\n')[0] ?? '').trim();
37
+ }
package/dist/init.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ export declare const hookCommand = "node node_modules/tslaws/hooks/claude-hook.mjs";
2
+ export declare const agentsBegin = "<!-- tslaws:begin -->";
3
+ export declare const agentsEnd = "<!-- tslaws:end -->";
4
+ export declare const nextStep = "Next, a person at a terminal runs `tslaws accept` to record the laws in tsc-laws.lock.";
5
+ interface HookEntry {
6
+ matcher?: string;
7
+ hooks?: {
8
+ type?: string;
9
+ command?: string;
10
+ }[];
11
+ }
12
+ export interface InitOptions {
13
+ cwd: string;
14
+ /** Overwrite tslaws.json, replace the AGENTS.md section and replace an unparseable settings file. */
15
+ force?: boolean;
16
+ }
17
+ /** Adds the template's hook entries to settings, keeping every other key and entry. Returns whether anything was added. */
18
+ export declare function mergeHooks(settings: Record<string, unknown>, template: {
19
+ hooks: Record<string, HookEntry[]>;
20
+ }): boolean;
21
+ /** Scaffolds a project for tslaws without overwriting its files. Returns one line per thing done or skipped. */
22
+ export declare function init(options: InitOptions): string[];
23
+ export {};
package/dist/init.js ADDED
@@ -0,0 +1,139 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ export const hookCommand = 'node node_modules/tslaws/hooks/claude-hook.mjs';
5
+ export const agentsBegin = '<!-- tslaws:begin -->';
6
+ export const agentsEnd = '<!-- tslaws:end -->';
7
+ export const nextStep = 'Next, a person at a terminal runs `tslaws accept` to record the laws in tsc-laws.lock.';
8
+ const hooksDir = join(dirname(fileURLToPath(import.meta.url)), '..', 'hooks');
9
+ const starterLaws = `// A starter law. A person owns this file: agents propose laws in *.proposed.laws.ts instead.
10
+ // Replace it with laws about your own code, then run \`tslaws accept\`.
11
+ import type { int } from 'tslaws';
12
+
13
+ export law additionCommutes(a: int, b: int) {
14
+ return a + b === b + a;
15
+ }
16
+ `;
17
+ function writeFile(file, text) {
18
+ mkdirSync(dirname(file), { recursive: true });
19
+ writeFileSync(file, text);
20
+ }
21
+ function hasLawsFile(dir) {
22
+ for (const entry of readdirSync(dir)) {
23
+ if (entry === 'node_modules' || entry === '.tslaws' || entry === '.git')
24
+ continue;
25
+ const full = join(dir, entry);
26
+ if (statSync(full).isDirectory()) {
27
+ if (hasLawsFile(full))
28
+ return true;
29
+ }
30
+ else if (entry.endsWith('.laws.ts'))
31
+ return true;
32
+ }
33
+ return false;
34
+ }
35
+ function commandsOf(entries) {
36
+ return entries.flatMap((e) => Array.isArray(e?.hooks) ? e.hooks.map((h) => String(h?.command)) : []);
37
+ }
38
+ /** Adds the template's hook entries to settings, keeping every other key and entry. Returns whether anything was added. */
39
+ export function mergeHooks(settings, template) {
40
+ let changed = false;
41
+ const existing = settings.hooks;
42
+ const hooks = typeof existing === 'object' && existing !== null && !Array.isArray(existing)
43
+ ? existing
44
+ : {};
45
+ for (const [event, entries] of Object.entries(template.hooks)) {
46
+ const current = Array.isArray(hooks[event]) ? hooks[event] : [];
47
+ const present = commandsOf(current);
48
+ for (const entry of entries) {
49
+ if (commandsOf([entry]).every((c) => present.includes(c)))
50
+ continue;
51
+ current.push(entry);
52
+ changed = true;
53
+ }
54
+ hooks[event] = current;
55
+ }
56
+ settings.hooks = hooks;
57
+ return changed;
58
+ }
59
+ function agentsSection() {
60
+ const snippet = readFileSync(join(hooksDir, 'AGENTS.snippet.md'), 'utf8').trim();
61
+ return `${agentsBegin}\n${snippet}\n${agentsEnd}\n`;
62
+ }
63
+ function initAgents(cwd, force) {
64
+ const file = join(cwd, 'AGENTS.md');
65
+ const section = agentsSection();
66
+ if (!existsSync(file)) {
67
+ writeFile(file, section);
68
+ return 'wrote AGENTS.md';
69
+ }
70
+ const text = readFileSync(file, 'utf8');
71
+ const begin = text.indexOf(agentsBegin);
72
+ const end = text.indexOf(agentsEnd);
73
+ if (begin >= 0 && end > begin) {
74
+ if (!force)
75
+ return 'kept AGENTS.md (laws section present; --force replaces it)';
76
+ writeFile(file, `${text.slice(0, begin)}${section.trimEnd()}${text.slice(end + agentsEnd.length)}`);
77
+ return 'updated AGENTS.md (laws section replaced)';
78
+ }
79
+ const sep = text === '' || text.endsWith('\n\n') ? '' : text.endsWith('\n') ? '\n' : '\n\n';
80
+ writeFile(file, `${text}${sep}${section}`);
81
+ return 'updated AGENTS.md (laws section appended)';
82
+ }
83
+ function initSettings(cwd, force) {
84
+ const file = join(cwd, '.claude', 'settings.json');
85
+ const template = JSON.parse(readFileSync(join(hooksDir, 'claude-settings.example.json'), 'utf8').replaceAll('node packages/tslaws/hooks/claude-hook.mjs', hookCommand));
86
+ const exists = existsSync(file);
87
+ let settings = {};
88
+ if (exists) {
89
+ try {
90
+ const parsed = JSON.parse(readFileSync(file, 'utf8'));
91
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
92
+ throw new Error('not an object');
93
+ settings = parsed;
94
+ }
95
+ catch {
96
+ if (!force)
97
+ return 'skipped .claude/settings.json (not valid JSON; fix it or use --force to replace it)';
98
+ }
99
+ }
100
+ const changed = mergeHooks(settings, template);
101
+ if (exists && !changed)
102
+ return 'kept .claude/settings.json (hooks already present)';
103
+ writeFile(file, `${JSON.stringify(settings, null, 2)}\n`);
104
+ return 'updated .claude/settings.json (tslaws hooks)';
105
+ }
106
+ /** Scaffolds a project for tslaws without overwriting its files. Returns one line per thing done or skipped. */
107
+ export function init(options) {
108
+ const { cwd, force = false } = options;
109
+ const out = [];
110
+ const config = join(cwd, 'tslaws.json');
111
+ if (existsSync(config) && !force)
112
+ out.push('kept tslaws.json (exists; --force overwrites)');
113
+ else {
114
+ writeFile(config, `${JSON.stringify({ cover: ['src/**/*.ts', '!src/**/*.laws.ts'] }, null, 2)}\n`);
115
+ out.push('wrote tslaws.json');
116
+ }
117
+ const ignore = join(cwd, '.gitignore');
118
+ const ignoreText = existsSync(ignore) ? readFileSync(ignore, 'utf8') : '';
119
+ // `.tslaws/regressions` is left out on purpose: a team may commit the counterexamples it has found.
120
+ const ignored = ['.tslaws/out', '.tslaws/mutants', '.tslaws/screenshots'];
121
+ const listed = ignoreText.split(/\r?\n/).map((l) => l.trim().replace(/^\//, '').replace(/\/$/, ''));
122
+ const missing = listed.includes('.tslaws') ? [] : ignored.filter((entry) => !listed.includes(entry));
123
+ if (missing.length === 0)
124
+ out.push('kept .gitignore (.tslaws already listed)');
125
+ else {
126
+ const lead = ignoreText === '' || ignoreText.endsWith('\n') ? '' : '\n';
127
+ writeFile(ignore, `${ignoreText}${lead}${missing.join('\n')}\n`);
128
+ out.push('updated .gitignore (.tslaws/out, mutants, screenshots)');
129
+ }
130
+ out.push(initAgents(cwd, force));
131
+ out.push(initSettings(cwd, force));
132
+ if (hasLawsFile(cwd))
133
+ out.push('kept no starter law added (a *.laws.ts file exists)');
134
+ else {
135
+ writeFile(join(cwd, 'src', 'example.laws.ts'), starterLaws);
136
+ out.push('wrote src/example.laws.ts (starter law)');
137
+ }
138
+ return out;
139
+ }
package/dist/lock.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ import type { ManifestLaw } from './types.ts';
2
+ export type LockEntries = Record<string, string>;
3
+ export interface Lock {
4
+ laws: LockEntries;
5
+ /** `file::name` of the functions a person exempted from coverage. */
6
+ exempt: string[];
7
+ }
8
+ export declare function lawKey(file: string, name: string): string;
9
+ export declare function lawHash(law: ManifestLaw): string;
10
+ export declare function readLock(path: string): Lock | undefined;
11
+ export declare function writeLock(path: string, laws: ManifestLaw[], exempt?: string[]): void;
12
+ export interface LockViolation {
13
+ key: string;
14
+ reason: 'changed' | 'added' | 'removed';
15
+ }
16
+ export declare function compareLock(lock: LockEntries | undefined, laws: ManifestLaw[]): LockViolation[];