tslaws 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -1
- package/dist/check.js +87 -17
- package/dist/cli.js +43 -3
- package/dist/coverage.d.ts +8 -0
- package/dist/coverage.js +18 -1
- package/dist/github.d.ts +123 -0
- package/dist/github.js +276 -0
- package/dist/githubCli.d.ts +53 -0
- package/dist/githubCli.js +535 -0
- package/dist/lock.d.ts +23 -0
- package/dist/lock.js +84 -0
- package/dist/propertyRun.d.ts +11 -0
- package/dist/propertyRun.js +23 -0
- package/dist/reporters.d.ts +3 -0
- package/dist/reporters.js +17 -0
- package/dist/smt.d.ts +16 -0
- package/dist/smt.js +43 -1
- package/dist/solvers.d.ts +31 -0
- package/dist/solvers.js +121 -0
- package/dist/symbolic.js +2 -2
- package/dist/types.d.ts +17 -0
- package/package.json +7 -7
package/dist/github.js
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
export const githubDefaults = {
|
|
2
|
+
accept: 'merge',
|
|
3
|
+
branch: 'master',
|
|
4
|
+
bot: 'github-actions[bot]',
|
|
5
|
+
approvers: ['author', 'reviewers'],
|
|
6
|
+
approvePullRequest: false,
|
|
7
|
+
requirePassing: true,
|
|
8
|
+
};
|
|
9
|
+
const approverKinds = ['author', 'reviewers', 'write', 'maintain', 'admin'];
|
|
10
|
+
/** Logins any workflow can act as. */
|
|
11
|
+
const sharedBots = new Set(['github-actions[bot]', 'github-actions', 'dependabot[bot]']);
|
|
12
|
+
/** Whether the bot is an account any workflow can act as, rather than a dedicated GitHub App. */
|
|
13
|
+
export function isSharedBot(config) {
|
|
14
|
+
return sharedBots.has(config.bot.toLowerCase());
|
|
15
|
+
}
|
|
16
|
+
/** Validates the `github` section of tslaws.json and fills in the defaults. */
|
|
17
|
+
export function parseGithubConfig(raw) {
|
|
18
|
+
const fail = (message) => {
|
|
19
|
+
throw new Error(`tslaws.json: "github": ${message}`);
|
|
20
|
+
};
|
|
21
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
|
|
22
|
+
return fail('must be an object');
|
|
23
|
+
const o = raw;
|
|
24
|
+
const known = ['accept', 'branch', 'bot', 'approvers', 'approvePullRequest', 'requirePassing'];
|
|
25
|
+
for (const key of Object.keys(o))
|
|
26
|
+
if (!known.includes(key))
|
|
27
|
+
fail(`unknown option "${key}"; supported: ${known.join(', ')}`);
|
|
28
|
+
if (o.accept !== undefined && o.accept !== 'merge' && o.accept !== 'comment')
|
|
29
|
+
fail(`"accept" must be "merge" or "comment", got ${JSON.stringify(o.accept)}`);
|
|
30
|
+
for (const key of ['branch', 'bot'])
|
|
31
|
+
if (o[key] !== undefined && (typeof o[key] !== 'string' || o[key] === ''))
|
|
32
|
+
fail(`"${key}" must be a non-empty string`);
|
|
33
|
+
if (o.approvers !== undefined &&
|
|
34
|
+
(!Array.isArray(o.approvers) ||
|
|
35
|
+
o.approvers.length === 0 ||
|
|
36
|
+
o.approvers.some((a) => !approverKinds.includes(a))))
|
|
37
|
+
fail(`"approvers" must be a non-empty array of ${approverKinds.join(', ')}`);
|
|
38
|
+
for (const key of ['approvePullRequest', 'requirePassing'])
|
|
39
|
+
if (o[key] !== undefined && typeof o[key] !== 'boolean')
|
|
40
|
+
fail(`"${key}" must be true or false`);
|
|
41
|
+
const config = { ...githubDefaults, ...o };
|
|
42
|
+
if (config.accept === 'comment' && isSharedBot(config))
|
|
43
|
+
fail(`accept "comment" needs "bot" set to a dedicated GitHub App, not ${JSON.stringify(config.bot)}: every workflow token acts as that account, so a pull request could forge approvals`);
|
|
44
|
+
return config;
|
|
45
|
+
}
|
|
46
|
+
const passingStatuses = new Set(['proved', 'bounded', 'tested']);
|
|
47
|
+
/** Joins the lock changes with what the check reported for each. */
|
|
48
|
+
export function proposalsOf(changes, report) {
|
|
49
|
+
const results = new Map();
|
|
50
|
+
for (const result of report?.results ?? [])
|
|
51
|
+
results.set(`${result.file.replaceAll('\\', '/')}::${result.name}`, result);
|
|
52
|
+
return changes.map((change) => {
|
|
53
|
+
const sep = change.key.lastIndexOf('::');
|
|
54
|
+
const file = change.key.slice(0, sep);
|
|
55
|
+
const name = change.key.slice(sep + 2);
|
|
56
|
+
const result = results.get(change.key);
|
|
57
|
+
const trivial = change.kind === 'exempt' || change.reason === 'removed';
|
|
58
|
+
const outcome = result?.proposal ??
|
|
59
|
+
(trivial
|
|
60
|
+
? { reason: change.kind === 'exempt' ? 'exempt' : 'removed', status: 'proved', method: 'lock' }
|
|
61
|
+
: undefined);
|
|
62
|
+
return {
|
|
63
|
+
key: change.key,
|
|
64
|
+
file,
|
|
65
|
+
name,
|
|
66
|
+
line: result?.line ?? 0,
|
|
67
|
+
kind: change.kind,
|
|
68
|
+
reason: change.reason,
|
|
69
|
+
fingerprint: change.fingerprint,
|
|
70
|
+
...(outcome === undefined ? {} : { outcome }),
|
|
71
|
+
passes: outcome !== undefined && passingStatuses.has(outcome.status),
|
|
72
|
+
};
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The `/tslaws accept ...` and `/tslaws reject ...` lines of a comment. Names are law names or `file::name` keys,
|
|
77
|
+
* separated by spaces or commas; a name with spaces is written in backticks or quotes.
|
|
78
|
+
*/
|
|
79
|
+
export function parseCommands(body) {
|
|
80
|
+
const commands = [];
|
|
81
|
+
for (const raw of body.split(/\r?\n/)) {
|
|
82
|
+
const line = raw.trim();
|
|
83
|
+
if (line.startsWith('>'))
|
|
84
|
+
continue; // a quoted command is someone else's
|
|
85
|
+
const match = /^\/tslaws\s+(accept|reject)\b(.*)$/i.exec(line);
|
|
86
|
+
if (match === null)
|
|
87
|
+
continue;
|
|
88
|
+
const verb = match[1].toLowerCase();
|
|
89
|
+
const rest = match[2].trim();
|
|
90
|
+
const names = [];
|
|
91
|
+
const token = /`([^`]+)`|"([^"]+)"|'([^']+)'|([^\s,]+)/g;
|
|
92
|
+
for (let m = token.exec(rest); m !== null; m = token.exec(rest))
|
|
93
|
+
names.push((m[1] ?? m[2] ?? m[3] ?? m[4]));
|
|
94
|
+
const all = names.length === 0 || names.some((n) => n.toLowerCase() === 'all');
|
|
95
|
+
commands.push({ verb, all, names: all ? [] : names });
|
|
96
|
+
}
|
|
97
|
+
return commands;
|
|
98
|
+
}
|
|
99
|
+
/** The proposals a command names: by `file::name` key, or by law name when that name is unambiguous. */
|
|
100
|
+
export function resolveNames(proposals, command) {
|
|
101
|
+
if (command.all)
|
|
102
|
+
return { matched: proposals, unknown: [], ambiguous: [] };
|
|
103
|
+
const matched = new Map();
|
|
104
|
+
const unknown = [];
|
|
105
|
+
const ambiguous = [];
|
|
106
|
+
for (const name of command.names) {
|
|
107
|
+
const byKey = proposals.filter((p) => p.key === name);
|
|
108
|
+
const byName = byKey.length > 0 ? byKey : proposals.filter((p) => p.name === name);
|
|
109
|
+
if (byName.length === 0)
|
|
110
|
+
unknown.push(name);
|
|
111
|
+
else if (byName.length > 1)
|
|
112
|
+
ambiguous.push(name);
|
|
113
|
+
else
|
|
114
|
+
matched.set(byName[0].fingerprint, byName[0]);
|
|
115
|
+
}
|
|
116
|
+
return { matched: [...matched.values()], unknown, ambiguous };
|
|
117
|
+
}
|
|
118
|
+
const markerStart = '<!-- tslaws-approval ';
|
|
119
|
+
const markerEnd = ' -->';
|
|
120
|
+
/** The first line of a record comment. A record counts only in a bot comment made of this line and markers alone. */
|
|
121
|
+
export const recordHeader = '<!-- tslaws-records -->';
|
|
122
|
+
export function approvalMarker(record) {
|
|
123
|
+
// Keys come from the pull request. Escape every character that could end the HTML comment or open another one, so
|
|
124
|
+
// the JSON can never close the marker early.
|
|
125
|
+
const json = JSON.stringify(record).replace(/[<>&-]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
|
|
126
|
+
return `${markerStart}${json}${markerEnd}`;
|
|
127
|
+
}
|
|
128
|
+
/** The body of a record comment: the header line, then one marker per line. Nothing from the pull request appears raw. */
|
|
129
|
+
export function recordComment(records) {
|
|
130
|
+
return [recordHeader, ...records.map(approvalMarker)].join('\n');
|
|
131
|
+
}
|
|
132
|
+
/** Text from a pull request (law names, file paths, unknown words), made inert in a markdown comment. */
|
|
133
|
+
export function inert(text) {
|
|
134
|
+
return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/@/g, '@');
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* The approval records in record comments the bot wrote, oldest first. A comment counts only if it is the header line
|
|
138
|
+
* followed by markers and nothing else. Records in anyone else's comment, or in a bot comment that also holds other
|
|
139
|
+
* text (such as text a pull request put there), are ignored.
|
|
140
|
+
*/
|
|
141
|
+
export function readApprovals(comments, bot) {
|
|
142
|
+
const records = [];
|
|
143
|
+
const sorted = [...comments].sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id - b.id);
|
|
144
|
+
for (const comment of sorted) {
|
|
145
|
+
if (comment.user.login !== bot)
|
|
146
|
+
continue;
|
|
147
|
+
const lines = comment.body.replace(/\r\n/g, '\n').trimEnd().split('\n');
|
|
148
|
+
if (lines[0] !== recordHeader || lines.length < 2)
|
|
149
|
+
continue;
|
|
150
|
+
const found = [];
|
|
151
|
+
for (const line of lines.slice(1)) {
|
|
152
|
+
if (!line.startsWith(markerStart) || !line.endsWith(markerEnd))
|
|
153
|
+
break;
|
|
154
|
+
const json = line.slice(markerStart.length, -markerEnd.length);
|
|
155
|
+
if (/[<>]|--/.test(json))
|
|
156
|
+
break;
|
|
157
|
+
try {
|
|
158
|
+
const record = JSON.parse(json);
|
|
159
|
+
if ((record.verb === 'accept' || record.verb === 'reject') &&
|
|
160
|
+
typeof record.by === 'string' &&
|
|
161
|
+
Array.isArray(record.items) &&
|
|
162
|
+
record.items.every((i) => typeof i?.key === 'string' && typeof i?.fingerprint === 'string'))
|
|
163
|
+
found.push(record);
|
|
164
|
+
else
|
|
165
|
+
break;
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (found.length === lines.length - 1)
|
|
172
|
+
records.push(...found);
|
|
173
|
+
}
|
|
174
|
+
return records;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* The fingerprints accepted by the records, latest word wins: a later reject withdraws an earlier accept of the same
|
|
178
|
+
* fingerprint. A fingerprint names one version of a law, so an edit after the accept leaves the new version unaccepted.
|
|
179
|
+
*/
|
|
180
|
+
export function acceptedFingerprints(records) {
|
|
181
|
+
const accepted = new Map();
|
|
182
|
+
for (const record of records)
|
|
183
|
+
for (const item of record.items) {
|
|
184
|
+
if (record.verb === 'accept')
|
|
185
|
+
accepted.set(item.fingerprint, record.by);
|
|
186
|
+
else
|
|
187
|
+
accepted.delete(item.fingerprint);
|
|
188
|
+
}
|
|
189
|
+
return accepted;
|
|
190
|
+
}
|
|
191
|
+
/** Which proposals the merge job accepts. */
|
|
192
|
+
export function decide(proposals, config, approvals) {
|
|
193
|
+
const accept = new Set();
|
|
194
|
+
const held = [];
|
|
195
|
+
for (const proposal of proposals) {
|
|
196
|
+
if (config.requirePassing && !proposal.passes) {
|
|
197
|
+
held.push({ proposal, why: proposal.outcome === undefined ? 'did not run' : `is ${proposal.outcome.status}` });
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if (config.accept === 'comment' && !approvals.has(proposal.fingerprint)) {
|
|
201
|
+
held.push({ proposal, why: 'nobody with authority accepted this version' });
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
accept.add(proposal.fingerprint);
|
|
205
|
+
}
|
|
206
|
+
return { accept, held };
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* The pull request's verdict: it fails when a law that is already accepted fails, when a proposal fails (a failing
|
|
210
|
+
* proposal is rejected outright), or in comment mode while a proposal waits for an accept.
|
|
211
|
+
*/
|
|
212
|
+
export function pullRequestVerdict(report, proposals, config, approvals) {
|
|
213
|
+
const problems = [];
|
|
214
|
+
if (!report.compileOk)
|
|
215
|
+
problems.push('the project does not compile');
|
|
216
|
+
const proposed = new Set(proposals.map((p) => p.key));
|
|
217
|
+
for (const result of report.results) {
|
|
218
|
+
const key = `${result.file.replaceAll('\\', '/')}::${result.name}`;
|
|
219
|
+
if (passingStatuses.has(result.status) || (result.status === 'tampered' && proposed.has(key)))
|
|
220
|
+
continue;
|
|
221
|
+
problems.push(`${result.status} ${inert(result.name)} (${inert(result.file)}:${result.line})${result.message ? `: ${inert(result.message)}` : ''}`);
|
|
222
|
+
}
|
|
223
|
+
for (const p of proposals) {
|
|
224
|
+
if (!p.passes)
|
|
225
|
+
problems.push(`proposal ${inert(p.name)} (${inert(p.file)}) ${p.outcome === undefined ? 'did not run' : `is ${p.outcome.status}`}`);
|
|
226
|
+
else if (config.accept === 'comment' && !approvals.has(p.fingerprint))
|
|
227
|
+
problems.push(`proposal ${inert(p.name)} (${inert(p.file)}) waits for \`/tslaws accept\``);
|
|
228
|
+
}
|
|
229
|
+
return { ok: problems.length === 0, problems };
|
|
230
|
+
}
|
|
231
|
+
// ---- rendering ------------------------------------------------------------------------------------------------------
|
|
232
|
+
export const stickyMarker = '<!-- tslaws-proposals -->';
|
|
233
|
+
/** The sticky comment's marker for a project: the root's is unchanged; another project's names its path. */
|
|
234
|
+
export function stickyMarkerFor(project = '') {
|
|
235
|
+
if (project === '')
|
|
236
|
+
return stickyMarker;
|
|
237
|
+
// Percent-encode every byte outside a small safe set (`-` and `%` included), so two paths never share a marker and
|
|
238
|
+
// no path can write `-->` to close the comment early.
|
|
239
|
+
const encoded = project.replace(/[^A-Za-z0-9/._@]/gu, (c) => [...new TextEncoder().encode(c)].map((b) => `%${b.toString(16).toUpperCase().padStart(2, '0')}`).join(''));
|
|
240
|
+
return `<!-- tslaws-proposals ${encoded} -->`;
|
|
241
|
+
}
|
|
242
|
+
const cell = (text) => inert(text).replace(/\|/g, '\\|').replace(/\r?\n/g, ' ');
|
|
243
|
+
function outcomeText(p) {
|
|
244
|
+
if (p.outcome === undefined)
|
|
245
|
+
return '⚠️ did not run';
|
|
246
|
+
const icon = p.passes ? '✅' : '❌';
|
|
247
|
+
const extra = [
|
|
248
|
+
p.outcome.counterexample && `counterexample \`${p.outcome.counterexample}\``,
|
|
249
|
+
!p.passes && p.outcome.message,
|
|
250
|
+
]
|
|
251
|
+
.filter(Boolean)
|
|
252
|
+
.join('; ');
|
|
253
|
+
return `${icon} ${p.outcome.status}${extra === '' ? '' : ` — ${extra}`}`;
|
|
254
|
+
}
|
|
255
|
+
const what = (p) => p.kind === 'exempt' ? `exemption ${p.reason}` : p.reason === 'level' ? 'level changed' : `law ${p.reason}`;
|
|
256
|
+
/** The sticky pull request comment: every proposal, what it did, and whether it will be accepted on merge. */
|
|
257
|
+
export function renderSticky(proposals, config, approvals, link, project = '') {
|
|
258
|
+
const title = project === '' ? '' : ` for \`${project.replace(/`/g, "'")}\``;
|
|
259
|
+
const head = `${stickyMarkerFor(project)}\n### tslaws proposals${title}\n\n`;
|
|
260
|
+
if (proposals.length === 0)
|
|
261
|
+
return `${head}No law, level or coverage exemption differs from \`tsc-laws.lock\`.\n`;
|
|
262
|
+
const rows = proposals.map((p) => {
|
|
263
|
+
const state = !p.passes && config.requirePassing
|
|
264
|
+
? '🚫 rejected while it fails'
|
|
265
|
+
: config.accept === 'merge'
|
|
266
|
+
? '⏳ accepted on merge'
|
|
267
|
+
: approvals.has(p.fingerprint)
|
|
268
|
+
? `👍 accepted by @${approvals.get(p.fingerprint)} (on merge)`
|
|
269
|
+
: '✋ waiting for `/tslaws accept`';
|
|
270
|
+
return `| ${cell(link(p))} | ${what(p)} | ${cell(outcomeText(p))} | ${state} |`;
|
|
271
|
+
});
|
|
272
|
+
const how = config.accept === 'merge'
|
|
273
|
+
? `Proposals that pass are written to \`tsc-laws.lock\` by the tslaws workflow when this pull request merges into \`${config.branch}\`. Failing proposals are never accepted.`
|
|
274
|
+
: `Reply \`/tslaws accept <law>\` (or \`/tslaws accept all\`) to accept, \`/tslaws reject <law>\` to withdraw. An accept covers the version shown here; a later edit needs a new accept. Accepted proposals are written to \`tsc-laws.lock\` when this pull request merges into \`${config.branch}\`.`;
|
|
275
|
+
return `${head}| Law | Change | If accepted | State |\n| --- | --- | --- | --- |\n${rows.join('\n')}\n\n${how}\n`;
|
|
276
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { type GithubConfig } from './github.ts';
|
|
2
|
+
import { type Lock } from './lock.ts';
|
|
3
|
+
import type { CheckOptions, ManifestLaw } from './types.ts';
|
|
4
|
+
export interface GithubContext {
|
|
5
|
+
cwd: string;
|
|
6
|
+
/**
|
|
7
|
+
* Where the project sits in the repository, repo-relative with '/' separators and no trailing slash ('' at the root).
|
|
8
|
+
* Every REST path and annotation names files from the repository root, so they carry it.
|
|
9
|
+
*/
|
|
10
|
+
projectPath?: string;
|
|
11
|
+
/** The check options for the whole project (every laws file, the lock at the root). */
|
|
12
|
+
options: CheckOptions;
|
|
13
|
+
env: NodeJS.ProcessEnv;
|
|
14
|
+
flags: Map<string, string | true>;
|
|
15
|
+
out: (text: string) => void;
|
|
16
|
+
err: (text: string) => void;
|
|
17
|
+
/** For tests: a stand-in for the GitHub REST API. */
|
|
18
|
+
api?: Api;
|
|
19
|
+
}
|
|
20
|
+
/** `--project-path`, else where `cwd` sits inside its git repository (`git rev-parse --show-prefix`), else ''. */
|
|
21
|
+
export declare function projectPathOf(cwd: string, flag: string | true | undefined): string;
|
|
22
|
+
export type Api = (method: string, path: string, body?: unknown) => Promise<unknown>;
|
|
23
|
+
interface PullRequest {
|
|
24
|
+
number: number;
|
|
25
|
+
user: {
|
|
26
|
+
login: string;
|
|
27
|
+
type: string;
|
|
28
|
+
};
|
|
29
|
+
head: {
|
|
30
|
+
sha: string;
|
|
31
|
+
};
|
|
32
|
+
base: {
|
|
33
|
+
ref: string;
|
|
34
|
+
sha: string;
|
|
35
|
+
};
|
|
36
|
+
requested_reviewers?: {
|
|
37
|
+
login: string;
|
|
38
|
+
}[];
|
|
39
|
+
merged?: boolean;
|
|
40
|
+
}
|
|
41
|
+
/** The `github` section of a tslaws.json text, with defaults. It must exist: it names the bot every check trusts. */
|
|
42
|
+
export declare function githubConfigOf(text: string | undefined): GithubConfig;
|
|
43
|
+
interface ProjectState {
|
|
44
|
+
laws: ManifestLaw[];
|
|
45
|
+
exempt: string[];
|
|
46
|
+
levels: Record<string, string> | undefined;
|
|
47
|
+
lock: Lock | undefined;
|
|
48
|
+
}
|
|
49
|
+
export declare function projectState(options: CheckOptions): ProjectState;
|
|
50
|
+
/** Why `login` may not accept on this pull request, or undefined when they may. */
|
|
51
|
+
export declare function refusal(api: Api, name: string, pr: PullRequest, login: string, type: string, config: GithubConfig): Promise<string | undefined>;
|
|
52
|
+
export declare function githubCommand(action: string | undefined, ctx: GithubContext): Promise<number>;
|
|
53
|
+
export {};
|