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.
- package/LICENSE +202 -0
- package/README.md +215 -2
- package/bin/tslaws.js +5 -0
- package/dist/adapters/angular.d.ts +42 -0
- package/dist/adapters/angular.js +40 -0
- package/dist/adapters/dom.d.ts +5 -0
- package/dist/adapters/dom.js +17 -0
- package/dist/adapters/element.d.ts +10 -0
- package/dist/adapters/element.js +28 -0
- package/dist/adapters/react.d.ts +24 -0
- package/dist/adapters/react.js +15 -0
- package/dist/api.d.ts +59 -0
- package/dist/api.js +103 -0
- package/dist/browser.d.ts +24 -0
- package/dist/browser.js +252 -0
- package/dist/browserApi.d.ts +62 -0
- package/dist/browserApi.js +139 -0
- package/dist/bundled.d.ts +17 -0
- package/dist/bundled.js +67 -0
- package/dist/check.d.ts +12 -0
- package/dist/check.js +269 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +360 -0
- package/dist/compile.d.ts +15 -0
- package/dist/compile.js +142 -0
- package/dist/component.d.ts +37 -0
- package/dist/component.js +99 -0
- package/dist/coverage.d.ts +40 -0
- package/dist/coverage.js +237 -0
- package/dist/e2e.d.ts +46 -0
- package/dist/e2e.js +322 -0
- package/dist/e2eApi.d.ts +80 -0
- package/dist/e2eApi.js +140 -0
- package/dist/generators.d.ts +18 -0
- package/dist/generators.js +184 -0
- package/dist/hints.d.ts +3 -0
- package/dist/hints.js +37 -0
- package/dist/init.d.ts +23 -0
- package/dist/init.js +139 -0
- package/dist/lock.d.ts +16 -0
- package/dist/lock.js +40 -0
- package/dist/mcp.d.ts +30 -0
- package/dist/mcp.js +301 -0
- package/dist/mutate.d.ts +54 -0
- package/dist/mutate.js +293 -0
- package/dist/promote.d.ts +38 -0
- package/dist/promote.js +217 -0
- package/dist/property.d.ts +37 -0
- package/dist/property.js +172 -0
- package/dist/propertyWorker.d.ts +1 -0
- package/dist/propertyWorker.js +24 -0
- package/dist/queries.d.ts +37 -0
- package/dist/queries.js +297 -0
- package/dist/regressions.d.ts +31 -0
- package/dist/regressions.js +153 -0
- package/dist/reporters.d.ts +22 -0
- package/dist/reporters.js +160 -0
- package/dist/settings.d.ts +16 -0
- package/dist/settings.js +15 -0
- package/dist/smt.d.ts +33 -0
- package/dist/smt.js +396 -0
- package/dist/symbolic.d.ts +200 -0
- package/dist/symbolic.js +1727 -0
- package/dist/types.d.ts +77 -0
- package/dist/types.js +1 -0
- package/dist/ui.d.ts +16 -0
- package/dist/ui.js +326 -0
- package/dist/uiPage.d.ts +1 -0
- package/dist/uiPage.js +4 -0
- package/hooks/AGENTS.snippet.md +10 -0
- package/hooks/claude-hook.mjs +35 -0
- package/hooks/claude-settings.example.json +8 -0
- package/package.json +85 -4
- package/ui/index.html +1132 -0
package/dist/property.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { Worker } from 'node:worker_threads';
|
|
2
|
+
import { readdirSync, statSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import * as fc from 'fast-check';
|
|
5
|
+
import ts from 'typescript';
|
|
6
|
+
import { GeneratorFactory, UnsupportedType } from "./generators.js";
|
|
7
|
+
import { decodeExample, encodeExample } from "./regressions.js";
|
|
8
|
+
/** Every declaration file the compiler emitted: the laws' own do not import the code they are about. */
|
|
9
|
+
export function declarationFiles(outDir) {
|
|
10
|
+
const found = [];
|
|
11
|
+
const walk = (dir) => {
|
|
12
|
+
for (const entry of readdirSync(dir)) {
|
|
13
|
+
const full = join(dir, entry);
|
|
14
|
+
if (statSync(full).isDirectory()) {
|
|
15
|
+
if (entry !== 'smt')
|
|
16
|
+
walk(full);
|
|
17
|
+
}
|
|
18
|
+
else if (entry.endsWith('.d.ts'))
|
|
19
|
+
found.push(full);
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
walk(outDir);
|
|
23
|
+
return found;
|
|
24
|
+
}
|
|
25
|
+
export function dtsPath(outDir, file) {
|
|
26
|
+
return join(outDir, file.replace(/\.(ts|tsx|mts|cts)$/, '.d.ts'));
|
|
27
|
+
}
|
|
28
|
+
export function jsPath(outDir, file) {
|
|
29
|
+
return join(outDir, file.replace(/\.(ts|tsx|mts|cts)$/, '.js'));
|
|
30
|
+
}
|
|
31
|
+
/** What the prover models of `type`: numbers, `int`s, bigints, strings, booleans, arrays and records of them. */
|
|
32
|
+
export function shapeOf(checker, type) {
|
|
33
|
+
if ((type.aliasSymbol ?? type.getSymbol())?.getName() === 'int' &&
|
|
34
|
+
type.flags & (ts.TypeFlags.Intersection | ts.TypeFlags.Number))
|
|
35
|
+
return 'int';
|
|
36
|
+
if (type.flags & ts.TypeFlags.Number)
|
|
37
|
+
return 'number';
|
|
38
|
+
if (type.flags & ts.TypeFlags.BigInt)
|
|
39
|
+
return 'bigint';
|
|
40
|
+
if (type.flags & ts.TypeFlags.String)
|
|
41
|
+
return 'string';
|
|
42
|
+
if (type.flags & ts.TypeFlags.Boolean)
|
|
43
|
+
return 'boolean';
|
|
44
|
+
if (checker.isArrayType(type)) {
|
|
45
|
+
const element = shapeOf(checker, checker.getTypeArguments(type)[0]);
|
|
46
|
+
return element === undefined ? undefined : { array: element };
|
|
47
|
+
}
|
|
48
|
+
if (!(type.flags & ts.TypeFlags.Object) || checker.isTupleType(type))
|
|
49
|
+
return undefined;
|
|
50
|
+
if (type.getCallSignatures().length > 0 || checker.getIndexInfosOfType(type).length > 0)
|
|
51
|
+
return undefined;
|
|
52
|
+
const fields = {};
|
|
53
|
+
for (const property of checker.getPropertiesOfType(type)) {
|
|
54
|
+
const declaration = property.valueDeclaration ?? property.declarations?.[0];
|
|
55
|
+
if (declaration === undefined || property.flags & ts.SymbolFlags.Optional)
|
|
56
|
+
return undefined;
|
|
57
|
+
const shape = shapeOf(checker, checker.getTypeOfSymbolAtLocation(property, declaration));
|
|
58
|
+
if (shape === undefined)
|
|
59
|
+
return undefined;
|
|
60
|
+
fields[property.getName()] = shape;
|
|
61
|
+
}
|
|
62
|
+
return { fields };
|
|
63
|
+
}
|
|
64
|
+
export function typesOf(program, outDir, law) {
|
|
65
|
+
const checker = program.getTypeChecker();
|
|
66
|
+
const source = program.getSourceFile(dtsPath(outDir, law.file));
|
|
67
|
+
if (source === undefined)
|
|
68
|
+
throw new UnsupportedType(`no declaration output for ${law.file}`);
|
|
69
|
+
const moduleSymbol = checker.getSymbolAtLocation(source);
|
|
70
|
+
const exported = moduleSymbol === undefined
|
|
71
|
+
? undefined
|
|
72
|
+
: checker.getExportsOfModule(moduleSymbol).find((s) => s.getName() === law.name);
|
|
73
|
+
if (exported === undefined)
|
|
74
|
+
throw new UnsupportedType(`law ${law.name} is not in the declaration output`);
|
|
75
|
+
const signature = checker.getTypeOfSymbol(exported).getCallSignatures()[0];
|
|
76
|
+
if (signature === undefined)
|
|
77
|
+
throw new UnsupportedType(`law ${law.name} is not a function`);
|
|
78
|
+
const factory = new GeneratorFactory(checker);
|
|
79
|
+
const generators = [];
|
|
80
|
+
const shapes = [];
|
|
81
|
+
for (const parameter of signature.getParameters()) {
|
|
82
|
+
const declaration = parameter.valueDeclaration ?? parameter.declarations?.[0];
|
|
83
|
+
if (declaration === undefined)
|
|
84
|
+
throw new UnsupportedType(`parameter ${parameter.getName()} has no declaration`);
|
|
85
|
+
const type = checker.getTypeOfSymbolAtLocation(parameter, declaration);
|
|
86
|
+
shapes.push(shapeOf(checker, type));
|
|
87
|
+
const optional = (parameter.flags & ts.SymbolFlags.Optional) !== 0;
|
|
88
|
+
generators.push(factory.of(optional ? checker.getNonNullableType(type) : type));
|
|
89
|
+
}
|
|
90
|
+
return { generators, shapes };
|
|
91
|
+
}
|
|
92
|
+
export function isDiscard(error) {
|
|
93
|
+
return error instanceof Error && error.name === 'LawDiscard';
|
|
94
|
+
}
|
|
95
|
+
/** Runs `call` on generated inputs. `call` may be async (a law that waits, or one that runs in a browser). */
|
|
96
|
+
export async function runProperty(call, generators, options) {
|
|
97
|
+
const property = fc.asyncProperty(...generators, async (...args) => {
|
|
98
|
+
try {
|
|
99
|
+
return (await call(...args)) !== false;
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
if (isDiscard(error)) {
|
|
103
|
+
fc.pre(false);
|
|
104
|
+
return true;
|
|
105
|
+
}
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
return (await fc.check(property, {
|
|
110
|
+
numRuns: options.runs,
|
|
111
|
+
seed: options.seed,
|
|
112
|
+
maxSkipsPerRun: 100,
|
|
113
|
+
...(options.regressionExamples?.length ? { examples: options.regressionExamples.map(decodeExample) } : {}),
|
|
114
|
+
}));
|
|
115
|
+
}
|
|
116
|
+
export const runLaw = runProperty;
|
|
117
|
+
export const compilerOptions = {
|
|
118
|
+
skipLibCheck: true,
|
|
119
|
+
strict: true,
|
|
120
|
+
target: ts.ScriptTarget.ES2022,
|
|
121
|
+
module: ts.ModuleKind.CommonJS,
|
|
122
|
+
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
123
|
+
types: [],
|
|
124
|
+
};
|
|
125
|
+
export function summarise(details, options) {
|
|
126
|
+
const message = details.errorInstance instanceof Error ? details.errorInstance.message : undefined;
|
|
127
|
+
let encoded;
|
|
128
|
+
if (details.failed && details.counterexample !== null) {
|
|
129
|
+
try {
|
|
130
|
+
encoded = encodeExample(details.counterexample);
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
// Not storable (a class instance, a function): it is reported but not kept.
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return {
|
|
137
|
+
encoded,
|
|
138
|
+
regression: encoded !== undefined && options?.regressionExamples?.includes(encoded) === true,
|
|
139
|
+
failed: details.failed,
|
|
140
|
+
numRuns: details.numRuns,
|
|
141
|
+
seed: details.seed,
|
|
142
|
+
counterexample: details.counterexample === null ? undefined : fc.stringify(details.counterexample),
|
|
143
|
+
message,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
let worker;
|
|
147
|
+
/** Runs the property test of `law` in a worker, giving up on it after `options.propertyTimeoutMs`. */
|
|
148
|
+
export function runLawGuarded(outDir, law, options) {
|
|
149
|
+
const ext = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
|
|
150
|
+
if (worker === undefined) {
|
|
151
|
+
worker = new Worker(new URL(`./propertyWorker${ext}`, import.meta.url));
|
|
152
|
+
worker.unref();
|
|
153
|
+
}
|
|
154
|
+
const current = worker;
|
|
155
|
+
return new Promise((resolve, reject) => {
|
|
156
|
+
const timer = setTimeout(() => {
|
|
157
|
+
if (worker === current)
|
|
158
|
+
worker = undefined;
|
|
159
|
+
void current.terminate();
|
|
160
|
+
resolve('timeout');
|
|
161
|
+
}, options.propertyTimeoutMs ?? 30000);
|
|
162
|
+
current.once('message', (message) => {
|
|
163
|
+
clearTimeout(timer);
|
|
164
|
+
if (message.ok !== undefined)
|
|
165
|
+
resolve(message.ok);
|
|
166
|
+
else
|
|
167
|
+
reject(new Error(message.error));
|
|
168
|
+
});
|
|
169
|
+
// Functions cannot cross to the worker; it needs only the numbers.
|
|
170
|
+
current.postMessage({ outDir, law, options: { ...options, onEvent: undefined } });
|
|
171
|
+
});
|
|
172
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { parentPort } from 'node:worker_threads';
|
|
3
|
+
import ts from 'typescript';
|
|
4
|
+
import { compilerOptions, declarationFiles, jsPath, runLaw, summarise, typesOf } from "./property.js";
|
|
5
|
+
// Property tests run here so that a law over code that never terminates costs a timeout, not the whole check.
|
|
6
|
+
const require = createRequire(import.meta.url);
|
|
7
|
+
let programOf;
|
|
8
|
+
parentPort.on('message', async (request) => {
|
|
9
|
+
try {
|
|
10
|
+
const { outDir, law, options } = request;
|
|
11
|
+
if (programOf?.outDir !== outDir)
|
|
12
|
+
programOf = { outDir, program: ts.createProgram(declarationFiles(outDir), compilerOptions) };
|
|
13
|
+
const types = typesOf(programOf.program, outDir, law);
|
|
14
|
+
// The worker outlives a check, and the code may have been recompiled since the last one.
|
|
15
|
+
for (const loaded of Object.keys(require.cache))
|
|
16
|
+
if (loaded.startsWith(outDir))
|
|
17
|
+
delete require.cache[loaded];
|
|
18
|
+
const fn = require(jsPath(outDir, law.file))[law.name];
|
|
19
|
+
parentPort.postMessage({ ok: summarise(await runLaw(fn, types.generators, options), options) });
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
parentPort.postMessage({ error: error.message });
|
|
23
|
+
}
|
|
24
|
+
});
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export interface RoleOptions {
|
|
2
|
+
/** The accessible name: a string matches exactly (whitespace-normalised), a RegExp is tested. */
|
|
3
|
+
name?: string | RegExp;
|
|
4
|
+
pressed?: boolean;
|
|
5
|
+
checked?: boolean;
|
|
6
|
+
disabled?: boolean;
|
|
7
|
+
}
|
|
8
|
+
export type Matcher = string | RegExp;
|
|
9
|
+
/** The queries, bound to one root element. `Mounted.query` is one of these. */
|
|
10
|
+
export interface Queries {
|
|
11
|
+
byRole(role: string, options?: RoleOptions): HTMLElement;
|
|
12
|
+
allByRole(role: string, options?: RoleOptions): HTMLElement[];
|
|
13
|
+
byText(text: Matcher): HTMLElement;
|
|
14
|
+
allByText(text: Matcher): HTMLElement[];
|
|
15
|
+
byLabel(label: Matcher): HTMLElement;
|
|
16
|
+
allByLabel(label: Matcher): HTMLElement[];
|
|
17
|
+
byTestId(id: string): HTMLElement;
|
|
18
|
+
allByTestId(id: string): HTMLElement[];
|
|
19
|
+
/** The root's text with whitespace collapsed. */
|
|
20
|
+
text(): string;
|
|
21
|
+
}
|
|
22
|
+
/** Text with runs of whitespace collapsed to one space and the ends trimmed. */
|
|
23
|
+
export declare function text(el: Node): string;
|
|
24
|
+
/** The element's role: an explicit `role`, else the implicit role of its tag. Empty string when it has none. */
|
|
25
|
+
export declare function roleOf(el: Element): string;
|
|
26
|
+
/** An approximation of the accessible name: aria-labelledby, aria-label, a label, alt, value or content, then title. */
|
|
27
|
+
export declare function nameOf(el: Element): string;
|
|
28
|
+
export declare function allByRole(root: Element, role: string, options?: RoleOptions): HTMLElement[];
|
|
29
|
+
export declare function byRole(root: Element, role: string, options?: RoleOptions): HTMLElement;
|
|
30
|
+
export declare function allByText(root: Element, wanted: Matcher): HTMLElement[];
|
|
31
|
+
export declare function byText(root: Element, wanted: Matcher): HTMLElement;
|
|
32
|
+
export declare function allByLabel(root: Element, wanted: Matcher): HTMLElement[];
|
|
33
|
+
export declare function byLabel(root: Element, wanted: Matcher): HTMLElement;
|
|
34
|
+
export declare function allByTestId(root: Element, id: string): HTMLElement[];
|
|
35
|
+
export declare function byTestId(root: Element, id: string): HTMLElement;
|
|
36
|
+
/** The queries bound to `root`. */
|
|
37
|
+
export declare function within(root: Element): Queries;
|
package/dist/queries.js
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
/// <reference lib="dom" />
|
|
2
|
+
// Small testing-library-style queries over an element: by role (with an approximated accessible name), text, label and
|
|
3
|
+
// test id. No dependencies, so they bundle into any browser law.
|
|
4
|
+
/** Text with runs of whitespace collapsed to one space and the ends trimmed. */
|
|
5
|
+
export function text(el) {
|
|
6
|
+
return (el.textContent ?? '').replace(/\s+/g, ' ').trim();
|
|
7
|
+
}
|
|
8
|
+
const inputRoles = {
|
|
9
|
+
button: 'button',
|
|
10
|
+
submit: 'button',
|
|
11
|
+
reset: 'button',
|
|
12
|
+
image: 'button',
|
|
13
|
+
checkbox: 'checkbox',
|
|
14
|
+
radio: 'radio',
|
|
15
|
+
range: 'slider',
|
|
16
|
+
number: 'spinbutton',
|
|
17
|
+
search: 'searchbox',
|
|
18
|
+
email: 'textbox',
|
|
19
|
+
tel: 'textbox',
|
|
20
|
+
text: 'textbox',
|
|
21
|
+
url: 'textbox',
|
|
22
|
+
password: '',
|
|
23
|
+
};
|
|
24
|
+
/** The element's role: an explicit `role`, else the implicit role of its tag. Empty string when it has none. */
|
|
25
|
+
export function roleOf(el) {
|
|
26
|
+
const explicit = el.getAttribute('role')?.trim().split(/\s+/)[0];
|
|
27
|
+
if (explicit)
|
|
28
|
+
return explicit;
|
|
29
|
+
const tag = el.tagName.toLowerCase();
|
|
30
|
+
switch (tag) {
|
|
31
|
+
case 'button':
|
|
32
|
+
case 'summary':
|
|
33
|
+
return 'button';
|
|
34
|
+
case 'a':
|
|
35
|
+
case 'area':
|
|
36
|
+
return el.hasAttribute('href') ? 'link' : '';
|
|
37
|
+
case 'input':
|
|
38
|
+
return inputRoles[(el.getAttribute('type') ?? 'text').toLowerCase()] ?? 'textbox';
|
|
39
|
+
case 'select':
|
|
40
|
+
return el.hasAttribute('multiple') || Number(el.getAttribute('size') ?? 0) > 1 ? 'listbox' : 'combobox';
|
|
41
|
+
case 'textarea':
|
|
42
|
+
return 'textbox';
|
|
43
|
+
case 'h1':
|
|
44
|
+
case 'h2':
|
|
45
|
+
case 'h3':
|
|
46
|
+
case 'h4':
|
|
47
|
+
case 'h5':
|
|
48
|
+
case 'h6':
|
|
49
|
+
return 'heading';
|
|
50
|
+
case 'li':
|
|
51
|
+
return 'listitem';
|
|
52
|
+
case 'ul':
|
|
53
|
+
case 'ol':
|
|
54
|
+
return 'list';
|
|
55
|
+
case 'img':
|
|
56
|
+
return el.getAttribute('alt') === '' ? 'presentation' : 'img';
|
|
57
|
+
case 'nav':
|
|
58
|
+
return 'navigation';
|
|
59
|
+
case 'main':
|
|
60
|
+
return 'main';
|
|
61
|
+
case 'form':
|
|
62
|
+
return 'form';
|
|
63
|
+
case 'header':
|
|
64
|
+
return 'banner';
|
|
65
|
+
case 'footer':
|
|
66
|
+
return 'contentinfo';
|
|
67
|
+
case 'aside':
|
|
68
|
+
return 'complementary';
|
|
69
|
+
case 'table':
|
|
70
|
+
return 'table';
|
|
71
|
+
case 'tr':
|
|
72
|
+
return 'row';
|
|
73
|
+
case 'td':
|
|
74
|
+
return 'cell';
|
|
75
|
+
case 'th':
|
|
76
|
+
return 'columnheader';
|
|
77
|
+
case 'dialog':
|
|
78
|
+
return 'dialog';
|
|
79
|
+
case 'progress':
|
|
80
|
+
return 'progressbar';
|
|
81
|
+
case 'option':
|
|
82
|
+
return 'option';
|
|
83
|
+
case 'article':
|
|
84
|
+
return 'article';
|
|
85
|
+
case 'hr':
|
|
86
|
+
return 'separator';
|
|
87
|
+
case 'section':
|
|
88
|
+
return el.hasAttribute('aria-label') || el.hasAttribute('aria-labelledby') ? 'region' : '';
|
|
89
|
+
default:
|
|
90
|
+
return '';
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function idText(el, ids) {
|
|
94
|
+
const doc = el.ownerDocument;
|
|
95
|
+
return ids
|
|
96
|
+
.split(/\s+/)
|
|
97
|
+
.map((id) => doc.getElementById(id))
|
|
98
|
+
.filter((x) => x !== null)
|
|
99
|
+
.map(text)
|
|
100
|
+
.join(' ');
|
|
101
|
+
}
|
|
102
|
+
function labelsOf(el) {
|
|
103
|
+
const labels = [];
|
|
104
|
+
const doc = el.ownerDocument;
|
|
105
|
+
if (el.id)
|
|
106
|
+
for (const l of Array.from(doc.querySelectorAll('label')))
|
|
107
|
+
if (l.htmlFor === el.id)
|
|
108
|
+
labels.push(text(l));
|
|
109
|
+
const wrapping = el.closest('label');
|
|
110
|
+
if (wrapping !== null)
|
|
111
|
+
labels.push(text(wrapping));
|
|
112
|
+
return labels;
|
|
113
|
+
}
|
|
114
|
+
/** An approximation of the accessible name: aria-labelledby, aria-label, a label, alt, value or content, then title. */
|
|
115
|
+
export function nameOf(el) {
|
|
116
|
+
const by = el.getAttribute('aria-labelledby');
|
|
117
|
+
if (by) {
|
|
118
|
+
const joined = idText(el, by);
|
|
119
|
+
if (joined)
|
|
120
|
+
return joined;
|
|
121
|
+
}
|
|
122
|
+
const aria = el.getAttribute('aria-label')?.trim();
|
|
123
|
+
if (aria)
|
|
124
|
+
return aria;
|
|
125
|
+
const tag = el.tagName.toLowerCase();
|
|
126
|
+
if (tag === 'input' || tag === 'select' || tag === 'textarea') {
|
|
127
|
+
const labels = labelsOf(el);
|
|
128
|
+
if (labels[0])
|
|
129
|
+
return labels[0];
|
|
130
|
+
const type = (el.getAttribute('type') ?? '').toLowerCase();
|
|
131
|
+
if (tag === 'input' && ['button', 'submit', 'reset'].includes(type)) {
|
|
132
|
+
return el.value || (type === 'submit' ? 'Submit' : type === 'reset' ? 'Reset' : '');
|
|
133
|
+
}
|
|
134
|
+
const placeholder = el.getAttribute('placeholder');
|
|
135
|
+
if (placeholder)
|
|
136
|
+
return placeholder;
|
|
137
|
+
}
|
|
138
|
+
if (tag === 'img' || (tag === 'input' && el.getAttribute('type') === 'image')) {
|
|
139
|
+
const alt = el.getAttribute('alt');
|
|
140
|
+
if (alt)
|
|
141
|
+
return alt.trim();
|
|
142
|
+
}
|
|
143
|
+
const content = text(el);
|
|
144
|
+
if (content)
|
|
145
|
+
return content;
|
|
146
|
+
return el.getAttribute('title')?.trim() ?? '';
|
|
147
|
+
}
|
|
148
|
+
function matches(actual, wanted) {
|
|
149
|
+
if (typeof wanted === 'string')
|
|
150
|
+
return actual === wanted.replace(/\s+/g, ' ').trim();
|
|
151
|
+
wanted.lastIndex = 0;
|
|
152
|
+
return wanted.test(actual);
|
|
153
|
+
}
|
|
154
|
+
function describeMatcher(wanted) {
|
|
155
|
+
return typeof wanted === 'string' ? JSON.stringify(wanted) : String(wanted);
|
|
156
|
+
}
|
|
157
|
+
function hidden(el) {
|
|
158
|
+
return el.hasAttribute('hidden') || el.getAttribute('aria-hidden') === 'true';
|
|
159
|
+
}
|
|
160
|
+
function elements(root) {
|
|
161
|
+
return Array.from(root.querySelectorAll('*')).filter((e) => !hidden(e));
|
|
162
|
+
}
|
|
163
|
+
function isChecked(el) {
|
|
164
|
+
if (el instanceof HTMLInputElement && (el.type === 'checkbox' || el.type === 'radio'))
|
|
165
|
+
return el.checked;
|
|
166
|
+
return el.getAttribute('aria-checked') === 'true';
|
|
167
|
+
}
|
|
168
|
+
function isDisabled(el) {
|
|
169
|
+
return el.disabled === true || el.getAttribute('aria-disabled') === 'true';
|
|
170
|
+
}
|
|
171
|
+
function describeOptions(options) {
|
|
172
|
+
const parts = [];
|
|
173
|
+
if (options.name !== undefined)
|
|
174
|
+
parts.push(`name ${describeMatcher(options.name)}`);
|
|
175
|
+
for (const key of ['pressed', 'checked', 'disabled'])
|
|
176
|
+
if (options[key] !== undefined)
|
|
177
|
+
parts.push(`${key} ${options[key]}`);
|
|
178
|
+
return parts.length > 0 ? ` with ${parts.join(', ')}` : '';
|
|
179
|
+
}
|
|
180
|
+
function summary(root, pick) {
|
|
181
|
+
const lines = elements(root)
|
|
182
|
+
.map(pick)
|
|
183
|
+
.filter((s) => s !== undefined);
|
|
184
|
+
const shown = lines.slice(0, 20).map((l) => ` ${l}`);
|
|
185
|
+
if (lines.length > 20)
|
|
186
|
+
shown.push(` ... and ${lines.length - 20} more`);
|
|
187
|
+
return shown.length > 0 ? shown.join('\n') : ' (nothing)';
|
|
188
|
+
}
|
|
189
|
+
function one(found, what, listing) {
|
|
190
|
+
if (found.length === 0)
|
|
191
|
+
throw new Error(`no element ${what}. Found:\n${listing()}`);
|
|
192
|
+
if (found.length > 1)
|
|
193
|
+
throw new Error(`${found.length} elements ${what}; use the all* query or be more specific`);
|
|
194
|
+
return found[0];
|
|
195
|
+
}
|
|
196
|
+
export function allByRole(root, role, options = {}) {
|
|
197
|
+
return elements(root).filter((el) => {
|
|
198
|
+
if (roleOf(el) !== role)
|
|
199
|
+
return false;
|
|
200
|
+
if (options.name !== undefined && !matches(nameOf(el), options.name))
|
|
201
|
+
return false;
|
|
202
|
+
if (options.pressed !== undefined && (el.getAttribute('aria-pressed') === 'true') !== options.pressed)
|
|
203
|
+
return false;
|
|
204
|
+
if (options.checked !== undefined && isChecked(el) !== options.checked)
|
|
205
|
+
return false;
|
|
206
|
+
if (options.disabled !== undefined && isDisabled(el) !== options.disabled)
|
|
207
|
+
return false;
|
|
208
|
+
return true;
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
export function byRole(root, role, options = {}) {
|
|
212
|
+
return one(allByRole(root, role, options), `with role ${JSON.stringify(role)}${describeOptions(options)}`, () => summary(root, (el) => {
|
|
213
|
+
const r = roleOf(el);
|
|
214
|
+
if (r === '')
|
|
215
|
+
return undefined;
|
|
216
|
+
const n = nameOf(el);
|
|
217
|
+
return n ? `${r} ${JSON.stringify(n.length > 60 ? `${n.slice(0, 57)}...` : n)}` : r;
|
|
218
|
+
}));
|
|
219
|
+
}
|
|
220
|
+
// An element's own text: its direct text nodes, so a wrapper does not match its child's text.
|
|
221
|
+
function ownText(el) {
|
|
222
|
+
return Array.from(el.childNodes)
|
|
223
|
+
.filter((n) => n.nodeType === Node.TEXT_NODE)
|
|
224
|
+
.map((n) => n.textContent ?? '')
|
|
225
|
+
.join('')
|
|
226
|
+
.replace(/\s+/g, ' ')
|
|
227
|
+
.trim();
|
|
228
|
+
}
|
|
229
|
+
export function allByText(root, wanted) {
|
|
230
|
+
return elements(root).filter((el) => {
|
|
231
|
+
if (['script', 'style'].includes(el.tagName.toLowerCase()))
|
|
232
|
+
return false;
|
|
233
|
+
const own = ownText(el);
|
|
234
|
+
return own !== '' && matches(own, wanted);
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
export function byText(root, wanted) {
|
|
238
|
+
return one(allByText(root, wanted), `with text ${describeMatcher(wanted)}`, () => summary(root, (el) => {
|
|
239
|
+
const own = ownText(el);
|
|
240
|
+
return own === ''
|
|
241
|
+
? undefined
|
|
242
|
+
: `<${el.tagName.toLowerCase()}> ${JSON.stringify(own.length > 60 ? `${own.slice(0, 57)}...` : own)}`;
|
|
243
|
+
}));
|
|
244
|
+
}
|
|
245
|
+
export function allByLabel(root, wanted) {
|
|
246
|
+
const found = new Set();
|
|
247
|
+
const doc = root.ownerDocument;
|
|
248
|
+
for (const label of Array.from(root.querySelectorAll('label'))) {
|
|
249
|
+
if (!matches(text(label), wanted))
|
|
250
|
+
continue;
|
|
251
|
+
const target = label.control ?? (label.htmlFor ? doc.getElementById(label.htmlFor) : null);
|
|
252
|
+
if (target instanceof HTMLElement)
|
|
253
|
+
found.add(target);
|
|
254
|
+
}
|
|
255
|
+
for (const el of elements(root)) {
|
|
256
|
+
const aria = el.getAttribute('aria-label');
|
|
257
|
+
if (aria !== null && matches(aria.replace(/\s+/g, ' ').trim(), wanted))
|
|
258
|
+
found.add(el);
|
|
259
|
+
const by = el.getAttribute('aria-labelledby');
|
|
260
|
+
if (by && matches(idText(el, by), wanted))
|
|
261
|
+
found.add(el);
|
|
262
|
+
}
|
|
263
|
+
return Array.from(found).filter((el) => root.contains(el));
|
|
264
|
+
}
|
|
265
|
+
export function byLabel(root, wanted) {
|
|
266
|
+
return one(allByLabel(root, wanted), `labelled ${describeMatcher(wanted)}`, () => {
|
|
267
|
+
const labels = Array.from(root.querySelectorAll('label')).map((l) => ` label ${JSON.stringify(text(l))}`);
|
|
268
|
+
const aria = elements(root)
|
|
269
|
+
.filter((el) => el.hasAttribute('aria-label'))
|
|
270
|
+
.map((el) => ` aria-label ${JSON.stringify(el.getAttribute('aria-label'))}`);
|
|
271
|
+
const all = [...labels, ...aria];
|
|
272
|
+
return all.length > 0 ? all.join('\n') : ' (no labels)';
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
export function allByTestId(root, id) {
|
|
276
|
+
return Array.from(root.querySelectorAll('[data-testid]')).filter((el) => el.getAttribute('data-testid') === id);
|
|
277
|
+
}
|
|
278
|
+
export function byTestId(root, id) {
|
|
279
|
+
return one(allByTestId(root, id), `with data-testid ${JSON.stringify(id)}`, () => {
|
|
280
|
+
const ids = Array.from(root.querySelectorAll('[data-testid]')).map((el) => ` data-testid ${JSON.stringify(el.getAttribute('data-testid'))}`);
|
|
281
|
+
return ids.length > 0 ? ids.join('\n') : ' (no data-testid)';
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
/** The queries bound to `root`. */
|
|
285
|
+
export function within(root) {
|
|
286
|
+
return {
|
|
287
|
+
byRole: (role, options) => byRole(root, role, options),
|
|
288
|
+
allByRole: (role, options) => allByRole(root, role, options),
|
|
289
|
+
byText: (wanted) => byText(root, wanted),
|
|
290
|
+
allByText: (wanted) => allByText(root, wanted),
|
|
291
|
+
byLabel: (wanted) => byLabel(root, wanted),
|
|
292
|
+
allByLabel: (wanted) => allByLabel(root, wanted),
|
|
293
|
+
byTestId: (id) => byTestId(root, id),
|
|
294
|
+
allByTestId: (id) => allByTestId(root, id),
|
|
295
|
+
text: () => text(root),
|
|
296
|
+
};
|
|
297
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** The most examples kept per law. */
|
|
2
|
+
export declare const maxExamples = 20;
|
|
3
|
+
export declare const regressionMessage = "regression: a previously found counterexample still fails";
|
|
4
|
+
type Json = null | boolean | string | number | Json[] | {
|
|
5
|
+
[key: string]: Json;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Turns an arbitrary JS value into JSON that `decodeValue` turns back into an equal value. Plain JSON values stay as
|
|
9
|
+
* they are; everything JSON cannot say is a `{"$t": ...}` object, and plain objects are wrapped so a key named `$t`
|
|
10
|
+
* cannot be mistaken for a tag.
|
|
11
|
+
*/
|
|
12
|
+
export declare function encodeValue(value: unknown): Json;
|
|
13
|
+
export declare function decodeValue(json: Json): unknown;
|
|
14
|
+
/** One example (the arguments of a law) as text: the same text for equal arguments, so it also serves as identity. */
|
|
15
|
+
export declare function encodeExample(args: unknown[]): string;
|
|
16
|
+
export declare function decodeExample(text: string): unknown[];
|
|
17
|
+
/** `.tslaws/regressions/<law file with / as __>/<law>.json` */
|
|
18
|
+
export declare function regressionFile(cwd: string, file: string, name: string): string;
|
|
19
|
+
/** The stored examples of a law as the texts `encodeExample` makes, newest first. */
|
|
20
|
+
export declare function loadExamples(cwd: string, file: string, name: string): string[];
|
|
21
|
+
/** Stores `args` as the newest example; an equal older one moves to the front. Returns false when `args` cannot be stored. */
|
|
22
|
+
export declare function saveExample(cwd: string, file: string, name: string, args: unknown[]): boolean;
|
|
23
|
+
export interface CorpusEntry {
|
|
24
|
+
file: string;
|
|
25
|
+
law: string;
|
|
26
|
+
count: number;
|
|
27
|
+
}
|
|
28
|
+
export declare function listCorpus(cwd: string): CorpusEntry[];
|
|
29
|
+
/** Deletes the whole corpus. Returns whether there was one. */
|
|
30
|
+
export declare function clearCorpus(cwd: string): boolean;
|
|
31
|
+
export {};
|