tslaws 0.10.0 → 1.0.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 +7 -2
- package/bin/tslaws.js +8 -2
- package/dist/browser.d.ts +1 -1
- package/dist/browser.js +25 -5
- package/dist/bundled.js +2 -2
- package/dist/bundlerPlugins.d.ts +2 -0
- package/dist/bundlerPlugins.js +7 -0
- package/dist/certificates.d.ts +139 -0
- package/dist/certificates.js +433 -0
- package/dist/chc.d.ts +85 -0
- package/dist/chc.js +298 -0
- package/dist/check.d.ts +13 -1
- package/dist/check.js +211 -27
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +175 -34
- package/dist/compile.d.ts +15 -5
- package/dist/compile.js +198 -69
- package/dist/coverage.d.ts +38 -1
- package/dist/coverage.js +94 -12
- package/dist/e2eApi.js +3 -1
- package/dist/generators.js +12 -2
- package/dist/github.d.ts +49 -5
- package/dist/github.js +107 -24
- package/dist/githubCli.d.ts +28 -0
- package/dist/githubCli.js +1039 -211
- package/dist/hints.js +2 -1
- package/dist/init.js +42 -0
- package/dist/isolate.d.ts +28 -0
- package/dist/isolate.js +262 -0
- package/dist/isolatedCheck.d.ts +1 -0
- package/dist/isolatedCheck.js +16 -0
- package/dist/lawHost.d.ts +50 -0
- package/dist/lawHost.js +199 -0
- package/dist/lawRuntime.d.ts +39 -0
- package/dist/lawRuntime.js +242 -0
- package/dist/lock.d.ts +49 -9
- package/dist/lock.js +132 -21
- package/dist/mcp.js +28 -7
- package/dist/mutate.d.ts +4 -0
- package/dist/mutate.js +7 -1
- package/dist/plan.d.ts +1 -0
- package/dist/plan.js +4 -0
- package/dist/pluginHooks.d.ts +16 -0
- package/dist/pluginHooks.js +48 -0
- package/dist/pluginHost.d.ts +5 -0
- package/dist/pluginHost.js +43 -0
- package/dist/pluginWorker.d.ts +1 -0
- package/dist/pluginWorker.js +40 -0
- package/dist/plural.d.ts +2 -0
- package/dist/plural.js +4 -0
- package/dist/pool.d.ts +80 -7
- package/dist/pool.js +222 -11
- package/dist/projects.d.ts +43 -1
- package/dist/projects.js +283 -11
- package/dist/promote.d.ts +56 -2
- package/dist/promote.js +429 -13
- package/dist/property.js +5 -1
- package/dist/propertyWorker.js +7 -0
- package/dist/proposals.d.ts +52 -4
- package/dist/proposals.js +484 -21
- package/dist/reporters.js +5 -1
- package/dist/runtimeEnv.d.ts +13 -5
- package/dist/runtimeEnv.js +48 -10
- package/dist/sandbox.d.ts +98 -0
- package/dist/sandbox.js +673 -0
- package/dist/sandboxGuard.d.ts +56 -0
- package/dist/sandboxGuard.js +249 -0
- package/dist/seal.d.ts +9 -0
- package/dist/seal.js +426 -0
- package/dist/security/cli.d.ts +6 -0
- package/dist/security/cli.js +39 -0
- package/dist/security/cwe.d.ts +14 -0
- package/dist/security/cwe.js +40 -0
- package/dist/security/deps/cache.d.ts +28 -0
- package/dist/security/deps/cache.js +107 -0
- package/dist/security/deps/config.d.ts +16 -0
- package/dist/security/deps/config.js +43 -0
- package/dist/security/deps/imports.d.ts +4 -0
- package/dist/security/deps/imports.js +33 -0
- package/dist/security/deps/lockfiles.d.ts +23 -0
- package/dist/security/deps/lockfiles.js +153 -0
- package/dist/security/deps/osv.d.ts +66 -0
- package/dist/security/deps/osv.js +137 -0
- package/dist/security/deps/run.d.ts +54 -0
- package/dist/security/deps/run.js +135 -0
- package/dist/security/deps/severity.d.ts +26 -0
- package/dist/security/deps/severity.js +78 -0
- package/dist/security/generators.d.ts +9 -0
- package/dist/security/generators.js +36 -0
- package/dist/security/index.d.ts +27 -0
- package/dist/security/index.js +18 -0
- package/dist/security/integers.d.ts +31 -0
- package/dist/security/integers.js +105 -0
- package/dist/security/law.d.ts +54 -0
- package/dist/security/law.js +54 -0
- package/dist/security/pathTraversal.d.ts +29 -0
- package/dist/security/pathTraversal.js +146 -0
- package/dist/security/prototypePollution.d.ts +30 -0
- package/dist/security/prototypePollution.js +142 -0
- package/dist/security/redirect.d.ts +21 -0
- package/dist/security/redirect.js +154 -0
- package/dist/security/redos.d.ts +21 -0
- package/dist/security/redos.js +93 -0
- package/dist/security/validation.d.ts +25 -0
- package/dist/security/validation.js +89 -0
- package/dist/security/xss.d.ts +21 -0
- package/dist/security/xss.js +90 -0
- package/dist/settings.d.ts +20 -0
- package/dist/settings.js +32 -0
- package/dist/smt.d.ts +29 -1
- package/dist/smt.js +239 -107
- package/dist/smtWorker.d.ts +1 -0
- package/dist/smtWorker.js +26 -0
- package/dist/solvers.d.ts +9 -0
- package/dist/solvers.js +11 -5
- package/dist/symbolic.d.ts +54 -1
- package/dist/symbolic.js +239 -13
- package/dist/tsconfigResolve.d.ts +28 -0
- package/dist/tsconfigResolve.js +141 -0
- package/dist/types.d.ts +28 -0
- package/hooks/claude-hook.mjs +2 -0
- package/package.json +18 -6
package/dist/pool.js
CHANGED
|
@@ -1,28 +1,200 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { availableParallelism, constants, freemem, setPriority } from 'node:os';
|
|
3
|
+
const gibibyte = 2 ** 30;
|
|
4
|
+
/**
|
|
5
|
+
* How many things run at once. A given number (flag, then `TSLAWS_JOBS`, then `jobs` in tslaws.json) is used as it is.
|
|
6
|
+
* Without one: the cores less one, so the machine stays usable, up to 8, and no more than one slot per GiB of free memory
|
|
7
|
+
* (a Z3 instance holds a large WebAssembly heap).
|
|
8
|
+
*/
|
|
9
|
+
export function resolveJobs(input) {
|
|
10
|
+
const given = (value) => value !== undefined && Number.isInteger(value) && value > 0 ? value : undefined;
|
|
11
|
+
const fromEnv = input.env === undefined || input.env.trim() === '' ? undefined : given(Number(input.env));
|
|
12
|
+
const chosen = given(input.flag) ?? fromEnv ?? given(input.config);
|
|
13
|
+
if (chosen !== undefined)
|
|
14
|
+
return chosen;
|
|
15
|
+
const byCores = Math.min(8, Math.max(1, input.cores - 1));
|
|
16
|
+
return Math.max(1, Math.min(byCores, Math.floor(input.freeBytes / gibibyte)));
|
|
17
|
+
}
|
|
18
|
+
let sources = {};
|
|
19
|
+
let cached;
|
|
20
|
+
/**
|
|
21
|
+
* Sets where the number of slots comes from (the command line flag, `jobs` of tslaws.json). An absent `flag` leaves the
|
|
22
|
+
* flag as it was; a `config` key replaces the config source even when it is undefined, so one project's `jobs` never
|
|
23
|
+
* carries over to the next project checked in the same process.
|
|
24
|
+
*/
|
|
25
|
+
export function configureJobs(next = {}) {
|
|
26
|
+
sources = {
|
|
27
|
+
flag: next.flag ?? sources.flag,
|
|
28
|
+
config: 'config' in next ? next.config : sources.config,
|
|
29
|
+
};
|
|
30
|
+
cached = undefined;
|
|
31
|
+
}
|
|
32
|
+
/** Forgets every configured source and the number worked out from them; for tests. */
|
|
33
|
+
export function resetJobs() {
|
|
34
|
+
sources = {};
|
|
35
|
+
cached = undefined;
|
|
36
|
+
}
|
|
37
|
+
/** The size of the CPU budget. Worked out once per configuration, so free memory does not move it mid-run. */
|
|
3
38
|
export function jobs() {
|
|
4
|
-
|
|
5
|
-
|
|
39
|
+
cached ??= resolveJobs({
|
|
40
|
+
...sources,
|
|
41
|
+
env: process.env.TSLAWS_JOBS,
|
|
42
|
+
cores: availableParallelism(),
|
|
43
|
+
freeBytes: freemem(),
|
|
44
|
+
});
|
|
45
|
+
return cached;
|
|
46
|
+
}
|
|
47
|
+
/** Runs below normal priority, so a solver does not starve the machine's other work. Failures are ignored. */
|
|
48
|
+
export function lowerPriority(pid) {
|
|
49
|
+
if (pid === undefined)
|
|
50
|
+
return;
|
|
51
|
+
try {
|
|
52
|
+
setPriority(pid, constants.priority.PRIORITY_BELOW_NORMAL);
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
// Not allowed, or the process is already gone: it simply runs at its usual priority.
|
|
56
|
+
}
|
|
6
57
|
}
|
|
58
|
+
/**
|
|
59
|
+
* Slots of CPU for everything heavy: a law run, a solve, a spawned solver, a property worker task, a sandboxed law
|
|
60
|
+
* process. One budget serves the whole process, so the pools below no longer each take every core.
|
|
61
|
+
*
|
|
62
|
+
* Nesting reuses the slot: work started inside a function that `run` is holding a slot for (a proof under the law that
|
|
63
|
+
* asked for it) takes no second slot, so a waiting law can never be starved by the work it is waiting on, and a budget
|
|
64
|
+
* of 1 cannot deadlock. A race or portfolio asks for one extra slot per additional member with `portfolio`, never
|
|
65
|
+
* waiting for it: with none free the members run one after another on the slot already held.
|
|
66
|
+
*/
|
|
67
|
+
export class Budget {
|
|
68
|
+
used = 0;
|
|
69
|
+
waiting = [];
|
|
70
|
+
held = new AsyncLocalStorage();
|
|
71
|
+
limit;
|
|
72
|
+
constructor(limit = jobs) {
|
|
73
|
+
this.limit = limit;
|
|
74
|
+
}
|
|
75
|
+
/** The slots in use now. */
|
|
76
|
+
get inUse() {
|
|
77
|
+
return this.used;
|
|
78
|
+
}
|
|
79
|
+
/** The most slots there may be. */
|
|
80
|
+
get size() {
|
|
81
|
+
return this.limit();
|
|
82
|
+
}
|
|
83
|
+
/** Whether this async context already holds a slot. */
|
|
84
|
+
get holding() {
|
|
85
|
+
return this.held.getStore() === true;
|
|
86
|
+
}
|
|
87
|
+
/** Runs `work` holding one slot, waiting for one when none is free; reuses the slot this context already holds. */
|
|
88
|
+
async run(work) {
|
|
89
|
+
if (this.holding)
|
|
90
|
+
return work();
|
|
91
|
+
await this.take();
|
|
92
|
+
try {
|
|
93
|
+
return await this.held.run(true, work);
|
|
94
|
+
}
|
|
95
|
+
finally {
|
|
96
|
+
this.give();
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/** Takes a slot if one is free right now; the returned function gives it back. */
|
|
100
|
+
tryHold() {
|
|
101
|
+
if (this.used >= this.limit())
|
|
102
|
+
return undefined;
|
|
103
|
+
this.used += 1;
|
|
104
|
+
let given = false;
|
|
105
|
+
return () => {
|
|
106
|
+
if (given)
|
|
107
|
+
return;
|
|
108
|
+
given = true;
|
|
109
|
+
this.give();
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Runs the tasks together, each past the first on an extra slot, and the rest one after another on the slot already
|
|
114
|
+
* held. Results come back in the order of the tasks.
|
|
115
|
+
*/
|
|
116
|
+
portfolio(tasks) {
|
|
117
|
+
return this.run(async () => {
|
|
118
|
+
const results = Array.from({ length: tasks.length });
|
|
119
|
+
const together = [];
|
|
120
|
+
const inTurn = [];
|
|
121
|
+
let failure;
|
|
122
|
+
tasks.forEach((task, index) => {
|
|
123
|
+
const release = index === 0 ? undefined : this.tryHold();
|
|
124
|
+
if (release === undefined) {
|
|
125
|
+
inTurn.push(index);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
together.push(this.held
|
|
129
|
+
.run(true, task)
|
|
130
|
+
.then((value) => {
|
|
131
|
+
results[index] = value;
|
|
132
|
+
}, (error) => {
|
|
133
|
+
failure ??= { error };
|
|
134
|
+
})
|
|
135
|
+
.finally(release));
|
|
136
|
+
});
|
|
137
|
+
for (const index of inTurn) {
|
|
138
|
+
try {
|
|
139
|
+
results[index] = await tasks[index]();
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
failure ??= { error };
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
await Promise.all(together);
|
|
146
|
+
if (failure !== undefined)
|
|
147
|
+
throw failure.error;
|
|
148
|
+
return results;
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
take() {
|
|
152
|
+
if (this.used < this.limit()) {
|
|
153
|
+
this.used += 1;
|
|
154
|
+
return Promise.resolve();
|
|
155
|
+
}
|
|
156
|
+
return new Promise((resolve) => this.waiting.push(resolve));
|
|
157
|
+
}
|
|
158
|
+
give() {
|
|
159
|
+
// A slot goes straight to the next one waiting, unless the budget has shrunk below what is in use.
|
|
160
|
+
const next = this.used > this.limit() ? undefined : this.waiting.shift();
|
|
161
|
+
if (next === undefined)
|
|
162
|
+
this.used -= 1;
|
|
163
|
+
else
|
|
164
|
+
next();
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
/** The one budget of this process. */
|
|
168
|
+
export const budget = new Budget();
|
|
7
169
|
/**
|
|
8
170
|
* A pool of workers where each request holds one exclusively, so a timeout can terminate its worker without
|
|
9
|
-
* disturbing a neighbour. Workers start on demand and are reused.
|
|
171
|
+
* disturbing a neighbour. Workers start on demand and are reused. `size` is read each time, so it may follow the budget.
|
|
172
|
+
* With `idleMs`, a worker that sits unused that long is terminated.
|
|
10
173
|
*/
|
|
11
174
|
export class WorkerPool {
|
|
12
175
|
idle = [];
|
|
176
|
+
timers = new Map();
|
|
13
177
|
waiting = [];
|
|
14
178
|
count = 0;
|
|
15
179
|
start;
|
|
16
180
|
size;
|
|
17
|
-
|
|
181
|
+
idleMs;
|
|
182
|
+
constructor(start, size = jobs, idleMs) {
|
|
18
183
|
this.start = start;
|
|
19
|
-
this.size = size;
|
|
184
|
+
this.size = typeof size === 'number' ? () => size : size;
|
|
185
|
+
this.idleMs = idleMs;
|
|
186
|
+
}
|
|
187
|
+
/** The workers this pool has started and not yet ended, busy or idle. */
|
|
188
|
+
get live() {
|
|
189
|
+
return this.count;
|
|
20
190
|
}
|
|
21
191
|
acquire() {
|
|
22
192
|
const free = this.idle.pop();
|
|
23
|
-
if (free !== undefined)
|
|
193
|
+
if (free !== undefined) {
|
|
194
|
+
this.untimed(free);
|
|
24
195
|
return Promise.resolve(free);
|
|
25
|
-
|
|
196
|
+
}
|
|
197
|
+
if (this.count < this.size()) {
|
|
26
198
|
this.count += 1;
|
|
27
199
|
return Promise.resolve(this.start());
|
|
28
200
|
}
|
|
@@ -30,8 +202,9 @@ export class WorkerPool {
|
|
|
30
202
|
}
|
|
31
203
|
/** Starts up to `n` workers now, so they finish loading while the caller does other work. */
|
|
32
204
|
warm(n) {
|
|
33
|
-
while (this.count < Math.min(n, this.size)) {
|
|
205
|
+
while (this.count < Math.min(n, this.size())) {
|
|
34
206
|
this.count += 1;
|
|
207
|
+
// Not timed: it waits for the first law, which may be a compile away.
|
|
35
208
|
this.idle.push(this.start());
|
|
36
209
|
}
|
|
37
210
|
}
|
|
@@ -40,7 +213,22 @@ export class WorkerPool {
|
|
|
40
213
|
if (next !== undefined)
|
|
41
214
|
next(worker);
|
|
42
215
|
else
|
|
43
|
-
this.
|
|
216
|
+
this.park(worker);
|
|
217
|
+
}
|
|
218
|
+
/** Terminates one idle worker, to make room elsewhere; false when none is idle. */
|
|
219
|
+
evictOne() {
|
|
220
|
+
const worker = this.idle.shift();
|
|
221
|
+
if (worker === undefined)
|
|
222
|
+
return false;
|
|
223
|
+
this.untimed(worker);
|
|
224
|
+
void worker.terminate();
|
|
225
|
+
this.count -= 1;
|
|
226
|
+
return true;
|
|
227
|
+
}
|
|
228
|
+
/** Terminates the idle workers, for a project that is done (a scratch copy that is about to be deleted). */
|
|
229
|
+
close() {
|
|
230
|
+
while (this.evictOne())
|
|
231
|
+
;
|
|
44
232
|
}
|
|
45
233
|
/** Terminates a worker that timed out or crashed; a waiting request gets a fresh one. */
|
|
46
234
|
discard(worker) {
|
|
@@ -51,4 +239,27 @@ export class WorkerPool {
|
|
|
51
239
|
else
|
|
52
240
|
next(this.start());
|
|
53
241
|
}
|
|
242
|
+
park(worker) {
|
|
243
|
+
this.idle.push(worker);
|
|
244
|
+
if (this.idleMs === undefined)
|
|
245
|
+
return;
|
|
246
|
+
const timer = setTimeout(() => {
|
|
247
|
+
const at = this.idle.indexOf(worker);
|
|
248
|
+
if (at < 0)
|
|
249
|
+
return;
|
|
250
|
+
this.idle.splice(at, 1);
|
|
251
|
+
this.timers.delete(worker);
|
|
252
|
+
void worker.terminate();
|
|
253
|
+
this.count -= 1;
|
|
254
|
+
}, this.idleMs);
|
|
255
|
+
timer.unref();
|
|
256
|
+
this.timers.set(worker, timer);
|
|
257
|
+
}
|
|
258
|
+
untimed(worker) {
|
|
259
|
+
const timer = this.timers.get(worker);
|
|
260
|
+
if (timer === undefined)
|
|
261
|
+
return;
|
|
262
|
+
clearTimeout(timer);
|
|
263
|
+
this.timers.delete(worker);
|
|
264
|
+
}
|
|
54
265
|
}
|
package/dist/projects.d.ts
CHANGED
|
@@ -3,13 +3,19 @@ export interface Project {
|
|
|
3
3
|
dir: string;
|
|
4
4
|
/** Directory relative to the repository root, with `/` separators; '' for the root itself. */
|
|
5
5
|
path: string;
|
|
6
|
+
/** Its tslaws.json says `"standalone": true`: root runs leave it alone unless it is named with `--project`. */
|
|
7
|
+
standalone: boolean;
|
|
6
8
|
}
|
|
7
9
|
export interface DiscoverOptions {
|
|
8
10
|
/** Keep projects whose `path` matches one of these globs (a leading `!` excludes). */
|
|
9
11
|
filter?: string[];
|
|
10
|
-
/** Keep only projects whose `path` is exactly one of these. */
|
|
12
|
+
/** Keep only projects whose `path` is exactly one of these. A standalone project is kept only when named here. */
|
|
11
13
|
only?: string[];
|
|
14
|
+
/** Keep standalone projects even when they are not named. For code that must know every project. */
|
|
15
|
+
standalone?: boolean;
|
|
12
16
|
}
|
|
17
|
+
/** The `workspaces` globs of a package.json text (an array, or `{ packages: [...] }`); [] when absent or unparsable. */
|
|
18
|
+
export declare function workspacesIn(text: string): string[];
|
|
13
19
|
/**
|
|
14
20
|
* The `packages:` list of pnpm-workspace.yaml. Only the plain shapes pnpm documents are read: a block list of
|
|
15
21
|
* (optionally quoted) globs, or a one-line `[a, b]`. That keeps this free of a YAML dependency.
|
|
@@ -26,3 +32,39 @@ export declare function discoverProjects(root: string, opts?: DiscoverOptions):
|
|
|
26
32
|
* tslaws.json has a `projects` list.
|
|
27
33
|
*/
|
|
28
34
|
export declare function isMonorepoRoot(cwd: string): boolean;
|
|
35
|
+
/** The files that decide which directories are projects, as text (undefined when the file is absent). */
|
|
36
|
+
export interface DiscoveryInputs {
|
|
37
|
+
tslaws?: string;
|
|
38
|
+
packageJson?: string;
|
|
39
|
+
pnpmWorkspace?: string;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* What `discoverProjects` would find, from a list of repository paths and the three discovery inputs instead of a
|
|
43
|
+
* directory: for reading a commit through the API. `files` are paths relative to the root. Sorted; '' is the root.
|
|
44
|
+
*/
|
|
45
|
+
export declare function discoverFromFiles(files: readonly string[], inputs: DiscoveryInputs): string[];
|
|
46
|
+
/** A canonical form of what the inputs say about discovery: equal signatures, same discovery. */
|
|
47
|
+
export declare function discoverySignature(inputs: DiscoveryInputs): string;
|
|
48
|
+
/** What changed against a base ref. */
|
|
49
|
+
export interface ChangeSet {
|
|
50
|
+
/** The merge-base of the ref and HEAD that the working tree was compared with. */
|
|
51
|
+
base: string;
|
|
52
|
+
/** Changed files relative to the directory asked about, with `/` separators; deleted files are included. */
|
|
53
|
+
files: string[];
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* What changed since `git merge-base <ref> HEAD`: committed, staged, unstaged and untracked files under `cwd` (ignored
|
|
57
|
+
* files do not count, nor do `.tslaws` and `node_modules`).
|
|
58
|
+
*/
|
|
59
|
+
export declare function changedSince(cwd: string, ref: string): ChangeSet;
|
|
60
|
+
export interface Affected {
|
|
61
|
+
project: Project;
|
|
62
|
+
/** Why it runs, in a few words. */
|
|
63
|
+
reason: string;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The projects of `root` that changed files (paths relative to `root`) can affect: the project that holds each file (the
|
|
67
|
+
* nearest enclosing one) and every project that depends on one, however indirectly. A change to a root config file or
|
|
68
|
+
* to a file a tslaws.json extends selects every project.
|
|
69
|
+
*/
|
|
70
|
+
export declare function affectedProjects(root: string, files: string[]): Affected[];
|
package/dist/projects.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
// Project discovery for a monorepo: a project is a directory holding a tslaws.json. Which directories to look in comes
|
|
2
2
|
// from the first source that names any: `projects` in the root tslaws.json, `workspaces` in package.json (npm, yarn
|
|
3
3
|
// and bun alike), or `packages:` in pnpm-workspace.yaml.
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
4
5
|
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
5
|
-
import { join, resolve } from 'node:path';
|
|
6
|
+
import { dirname, join, relative, resolve } from 'node:path';
|
|
6
7
|
import { projectsProblem, readConfig } from "./coverage.js";
|
|
7
8
|
import { globMatcher } from "./globs.js";
|
|
8
9
|
import { customLawFile } from "./lawFiles.js";
|
|
10
|
+
import { readResolution } from "./tsconfigResolve.js";
|
|
9
11
|
/** Directories never searched, for projects or for laws files. */
|
|
10
12
|
const skipped = new Set(['node_modules', '.git', 'dist', '.tslaws']);
|
|
11
13
|
/** `./packages/a/` as `packages/a`; `.` and `./` as ''. */
|
|
@@ -32,13 +34,11 @@ function projectsOf(dir) {
|
|
|
32
34
|
throw new Error(`tslaws.json: ${problem}`);
|
|
33
35
|
return raw.projects;
|
|
34
36
|
}
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
if (!existsSync(file))
|
|
38
|
-
return [];
|
|
37
|
+
/** The `workspaces` globs of a package.json text (an array, or `{ packages: [...] }`); [] when absent or unparsable. */
|
|
38
|
+
export function workspacesIn(text) {
|
|
39
39
|
let workspaces;
|
|
40
40
|
try {
|
|
41
|
-
workspaces =
|
|
41
|
+
workspaces = JSON.parse(text)?.workspaces;
|
|
42
42
|
}
|
|
43
43
|
catch {
|
|
44
44
|
return [];
|
|
@@ -46,6 +46,19 @@ function workspacesOf(dir) {
|
|
|
46
46
|
const list = Array.isArray(workspaces) ? workspaces : workspaces?.packages;
|
|
47
47
|
return Array.isArray(list) ? list.filter((entry) => typeof entry === 'string') : [];
|
|
48
48
|
}
|
|
49
|
+
function workspacesOf(dir) {
|
|
50
|
+
const file = join(dir, 'package.json');
|
|
51
|
+
return existsSync(file) ? workspacesIn(readFileSync(file, 'utf8')) : [];
|
|
52
|
+
}
|
|
53
|
+
/** Whether the tslaws.json in `dir` says `"standalone": true`. Read from the file itself: `extends` never carries it. */
|
|
54
|
+
function standaloneOf(dir) {
|
|
55
|
+
try {
|
|
56
|
+
return readJson(join(dir, 'tslaws.json'))?.standalone === true;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
49
62
|
/**
|
|
50
63
|
* The `packages:` list of pnpm-workspace.yaml. Only the plain shapes pnpm documents are read: a block list of
|
|
51
64
|
* (optionally quoted) globs, or a one-line `[a, b]`. That keeps this free of a YAML dependency.
|
|
@@ -101,17 +114,21 @@ function reaches(pattern, path) {
|
|
|
101
114
|
return true;
|
|
102
115
|
}
|
|
103
116
|
/** Directories (relative POSIX paths) under `root` that hold a tslaws.json and match `globs`. */
|
|
104
|
-
function
|
|
105
|
-
|
|
117
|
+
function normalisedGlobs(globs) {
|
|
118
|
+
return globs.map((glob) => {
|
|
106
119
|
const negated = glob.startsWith('!');
|
|
107
120
|
return `${negated ? '!' : ''}${normalise(negated ? glob.slice(1) : glob)}`;
|
|
108
121
|
});
|
|
122
|
+
}
|
|
123
|
+
/** Directories (relative POSIX paths) under `root` that hold a `marker` file and match `globs`. */
|
|
124
|
+
function matchingProjects(root, globs, marker = 'tslaws.json') {
|
|
125
|
+
const patterns = normalisedGlobs(globs);
|
|
109
126
|
const matches = globMatcher(patterns);
|
|
110
127
|
const includes = patterns.filter((glob) => !glob.startsWith('!'));
|
|
111
128
|
const found = [];
|
|
112
129
|
const walk = (path) => {
|
|
113
130
|
const dir = path === '' ? root : join(root, path);
|
|
114
|
-
if (path !== '' && matches(path) && existsSync(join(dir,
|
|
131
|
+
if (path !== '' && matches(path) && existsSync(join(dir, marker)))
|
|
115
132
|
found.push(path);
|
|
116
133
|
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
117
134
|
if (!entry.isDirectory() || skipped.has(entry.name))
|
|
@@ -162,11 +179,17 @@ export function discoverProjects(root, opts = {}) {
|
|
|
162
179
|
const paths = globs.length === 0 ? [] : matchingProjects(dir, globs);
|
|
163
180
|
if (existsSync(join(dir, 'tslaws.json')) && (listed === undefined || rootHasLaws(dir, paths)))
|
|
164
181
|
paths.push('');
|
|
165
|
-
let projects = paths.sort().map((path) => ({
|
|
182
|
+
let projects = paths.sort().map((path) => ({
|
|
183
|
+
dir: path === '' ? dir : join(dir, path),
|
|
184
|
+
path,
|
|
185
|
+
standalone: path !== '' && standaloneOf(join(dir, path)),
|
|
186
|
+
}));
|
|
166
187
|
if (opts.only !== undefined && opts.only.length > 0) {
|
|
167
188
|
const only = new Set(opts.only.map(normalise));
|
|
168
189
|
projects = projects.filter((project) => only.has(project.path));
|
|
169
190
|
}
|
|
191
|
+
else if (opts.standalone !== true)
|
|
192
|
+
projects = projects.filter((project) => !project.standalone);
|
|
170
193
|
if (opts.filter !== undefined && opts.filter.length > 0) {
|
|
171
194
|
const matches = globMatcher(opts.filter.map((glob) => (glob.startsWith('!') ? `!${normalise(glob.slice(1))}` : normalise(glob))));
|
|
172
195
|
projects = projects.filter((project) => matches(project.path));
|
|
@@ -180,6 +203,255 @@ export function discoverProjects(root, opts = {}) {
|
|
|
180
203
|
export function isMonorepoRoot(cwd) {
|
|
181
204
|
const dir = resolve(cwd);
|
|
182
205
|
if (!existsSync(join(dir, 'tslaws.json')))
|
|
183
|
-
return discoverProjects(dir).length > 0;
|
|
206
|
+
return discoverProjects(dir, { standalone: true }).length > 0;
|
|
184
207
|
return projectsOf(dir) !== undefined;
|
|
185
208
|
}
|
|
209
|
+
/** The project globs the inputs name, by the same precedence as `discoverProjects`; `listed` when tslaws.json names them. */
|
|
210
|
+
function globsFrom(inputs) {
|
|
211
|
+
let listed;
|
|
212
|
+
if (inputs.tslaws !== undefined) {
|
|
213
|
+
try {
|
|
214
|
+
const raw = JSON.parse(inputs.tslaws);
|
|
215
|
+
if (typeof raw === 'object' &&
|
|
216
|
+
raw !== null &&
|
|
217
|
+
raw.projects !== undefined &&
|
|
218
|
+
projectsProblem(raw.projects) === undefined)
|
|
219
|
+
listed = raw.projects;
|
|
220
|
+
}
|
|
221
|
+
catch {
|
|
222
|
+
// an unparsable file lists nothing; the caller reports it
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
const globs = listed ??
|
|
226
|
+
[
|
|
227
|
+
inputs.packageJson === undefined ? [] : workspacesIn(inputs.packageJson),
|
|
228
|
+
inputs.pnpmWorkspace === undefined ? [] : pnpmPackages(inputs.pnpmWorkspace),
|
|
229
|
+
].find((list) => list.length > 0) ??
|
|
230
|
+
[];
|
|
231
|
+
return { globs, listed: listed !== undefined };
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* What `discoverProjects` would find, from a list of repository paths and the three discovery inputs instead of a
|
|
235
|
+
* directory: for reading a commit through the API. `files` are paths relative to the root. Sorted; '' is the root.
|
|
236
|
+
*/
|
|
237
|
+
export function discoverFromFiles(files, inputs) {
|
|
238
|
+
const { globs, listed } = globsFrom(inputs);
|
|
239
|
+
const searched = files.filter((file) => !file.split('/').some((segment) => skipped.has(segment)));
|
|
240
|
+
const matches = globMatcher(normalisedGlobs(globs));
|
|
241
|
+
const paths = globs.length === 0
|
|
242
|
+
? []
|
|
243
|
+
: searched
|
|
244
|
+
.filter((file) => file.endsWith('/tslaws.json'))
|
|
245
|
+
.map((file) => file.slice(0, -'/tslaws.json'.length))
|
|
246
|
+
.filter((dir) => matches(dir));
|
|
247
|
+
if (inputs.tslaws !== undefined) {
|
|
248
|
+
const inProject = (file) => paths.some((dir) => file.startsWith(`${dir}/`));
|
|
249
|
+
const hasLaws = searched.some((file) => file === 'tsc-laws.lock' || (file.endsWith('.laws.ts') && !inProject(file)));
|
|
250
|
+
if (!listed || hasLaws)
|
|
251
|
+
paths.push('');
|
|
252
|
+
}
|
|
253
|
+
return [...new Set(paths)].sort();
|
|
254
|
+
}
|
|
255
|
+
/** A canonical form of what the inputs say about discovery: equal signatures, same discovery. */
|
|
256
|
+
export function discoverySignature(inputs) {
|
|
257
|
+
const { globs, listed } = globsFrom(inputs);
|
|
258
|
+
return JSON.stringify({ listed, globs });
|
|
259
|
+
}
|
|
260
|
+
function git(cwd, args) {
|
|
261
|
+
const run = spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 1 << 28 });
|
|
262
|
+
if (run.error !== undefined)
|
|
263
|
+
throw new Error(`git: ${run.error.message}`);
|
|
264
|
+
if (run.status !== 0)
|
|
265
|
+
throw new Error(run.stderr.trim() || `git ${args[0]} failed`);
|
|
266
|
+
return run.stdout;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* What changed since `git merge-base <ref> HEAD`: committed, staged, unstaged and untracked files under `cwd` (ignored
|
|
270
|
+
* files do not count, nor do `.tslaws` and `node_modules`).
|
|
271
|
+
*/
|
|
272
|
+
export function changedSince(cwd, ref) {
|
|
273
|
+
if (ref === '' || ref.startsWith('-'))
|
|
274
|
+
throw new Error('--changed needs a base ref, for example --changed origin/main');
|
|
275
|
+
let base;
|
|
276
|
+
try {
|
|
277
|
+
base = git(cwd, ['merge-base', ref, 'HEAD']).trim();
|
|
278
|
+
}
|
|
279
|
+
catch (error) {
|
|
280
|
+
throw new Error(`--changed ${ref}: ${error.message} (in CI, fetch the full history: fetch-depth: 0)`);
|
|
281
|
+
}
|
|
282
|
+
const split = (out) => out.split('\0').filter((file) => file !== '');
|
|
283
|
+
const tracked = split(git(cwd, ['diff', '--name-only', '-z', '--no-renames', '--relative', base]));
|
|
284
|
+
const untracked = split(git(cwd, ['ls-files', '--others', '--exclude-standard', '-z']));
|
|
285
|
+
const files = [...new Set([...tracked, ...untracked].map((file) => file.replaceAll('\\', '/')))]
|
|
286
|
+
.filter((file) => !file.split('/').some((segment) => segment === '.tslaws' || segment === 'node_modules'))
|
|
287
|
+
.sort();
|
|
288
|
+
return { base, files };
|
|
289
|
+
}
|
|
290
|
+
/** Files at the root that every project depends on: workspace, package and lock files, and the base tsconfigs. */
|
|
291
|
+
const rootConfig = /^(tslaws\.json|package\.json|package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|pnpm-workspace\.yaml|yarn\.lock|bun\.lockb?|tsconfig(\..+)?\.json)$/;
|
|
292
|
+
/** The files `extends` reaches from the tslaws.json in `dir`, as paths relative to `root`. */
|
|
293
|
+
function extendsChain(root, dir) {
|
|
294
|
+
const found = [];
|
|
295
|
+
let file = join(dir, 'tslaws.json');
|
|
296
|
+
for (let depth = 0; depth < 32; depth += 1) {
|
|
297
|
+
let parent;
|
|
298
|
+
try {
|
|
299
|
+
parent = readJson(file)?.extends;
|
|
300
|
+
}
|
|
301
|
+
catch {
|
|
302
|
+
return found;
|
|
303
|
+
}
|
|
304
|
+
if (typeof parent !== 'string' || parent === '')
|
|
305
|
+
return found;
|
|
306
|
+
file = resolve(dirname(file), parent);
|
|
307
|
+
found.push(normalise(relative(root, file)));
|
|
308
|
+
}
|
|
309
|
+
return found;
|
|
310
|
+
}
|
|
311
|
+
function manifestIn(dir) {
|
|
312
|
+
const file = join(dir, 'package.json');
|
|
313
|
+
if (!existsSync(file))
|
|
314
|
+
return undefined;
|
|
315
|
+
try {
|
|
316
|
+
const json = readJson(file);
|
|
317
|
+
const deps = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'].flatMap((key) => {
|
|
318
|
+
const table = json?.[key];
|
|
319
|
+
return typeof table === 'object' && table !== null ? Object.keys(table) : [];
|
|
320
|
+
});
|
|
321
|
+
return { name: typeof json?.name === 'string' ? json.name : undefined, deps };
|
|
322
|
+
}
|
|
323
|
+
catch {
|
|
324
|
+
return undefined;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
/** The directory one level up, as a relative POSIX path; '' above the first segment. */
|
|
328
|
+
const parentOf = (path) => (path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '');
|
|
329
|
+
/**
|
|
330
|
+
* The dependency edges between the projects and workspace packages of `root`, as `path -> paths it depends on`. Sources:
|
|
331
|
+
* package.json `dependencies`, `devDependencies`, `peerDependencies` and `optionalDependencies` that name another workspace package (a project
|
|
332
|
+
* without a package.json uses the nearest one above it); tsconfig `paths` targets that land in another package (a
|
|
333
|
+
* wildcard inside a target, as in `packages/*` + `/src`, counts as every package under it); and a nested package or
|
|
334
|
+
* project, which depends on the one around it.
|
|
335
|
+
*/
|
|
336
|
+
function dependencyGraph(root, projects) {
|
|
337
|
+
const globs = [workspacesOf(root), pnpmWorkspacesOf(root)].find((list) => list.length > 0) ?? [];
|
|
338
|
+
const packages = globs.length === 0 ? [] : matchingProjects(root, globs, 'package.json');
|
|
339
|
+
const nodes = new Set([...packages, ...projects.map((project) => project.path)]);
|
|
340
|
+
const dirOf = (path) => (path === '' ? root : join(root, path));
|
|
341
|
+
const names = new Map();
|
|
342
|
+
for (const node of nodes) {
|
|
343
|
+
const name = manifestIn(dirOf(node))?.name;
|
|
344
|
+
if (name !== undefined)
|
|
345
|
+
names.set(name, node);
|
|
346
|
+
}
|
|
347
|
+
const nearest = (path) => {
|
|
348
|
+
for (let at = path;; at = parentOf(at)) {
|
|
349
|
+
if (nodes.has(at))
|
|
350
|
+
return at;
|
|
351
|
+
if (at === '')
|
|
352
|
+
return undefined;
|
|
353
|
+
}
|
|
354
|
+
};
|
|
355
|
+
const graph = new Map();
|
|
356
|
+
for (const node of nodes) {
|
|
357
|
+
const edges = new Set();
|
|
358
|
+
graph.set(node, edges);
|
|
359
|
+
let manifest = manifestIn(dirOf(node));
|
|
360
|
+
for (let at = parentOf(node); manifest === undefined && node !== '' && at !== ''; at = parentOf(at))
|
|
361
|
+
manifest = manifestIn(dirOf(at));
|
|
362
|
+
for (const dep of manifest?.deps ?? []) {
|
|
363
|
+
const target = names.get(dep);
|
|
364
|
+
if (target !== undefined && target !== node)
|
|
365
|
+
edges.add(target);
|
|
366
|
+
}
|
|
367
|
+
const outer = node === '' ? undefined : nearest(parentOf(node));
|
|
368
|
+
if (outer !== undefined && outer !== '')
|
|
369
|
+
edges.add(outer);
|
|
370
|
+
}
|
|
371
|
+
for (const project of projects) {
|
|
372
|
+
let paths;
|
|
373
|
+
try {
|
|
374
|
+
paths = readResolution(project.dir)?.options.paths;
|
|
375
|
+
}
|
|
376
|
+
catch {
|
|
377
|
+
continue;
|
|
378
|
+
}
|
|
379
|
+
const edges = graph.get(project.path);
|
|
380
|
+
for (const target of Object.values(paths ?? {}).flat()) {
|
|
381
|
+
const [fixed = ''] = target.split('*', 1);
|
|
382
|
+
const at = normalise(relative(root, fixed).replaceAll('\\', '/'));
|
|
383
|
+
if (at === '..' || at.startsWith('../') || /^[a-z]:/i.test(at))
|
|
384
|
+
continue;
|
|
385
|
+
if (!target.includes('*')) {
|
|
386
|
+
const hit = nearest(at);
|
|
387
|
+
if (hit !== undefined && hit !== '')
|
|
388
|
+
edges.add(hit);
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
const dir = fixed.endsWith('/') ? at : parentOf(at);
|
|
392
|
+
const inside = nearest(dir);
|
|
393
|
+
if (inside !== undefined && inside !== '')
|
|
394
|
+
edges.add(inside);
|
|
395
|
+
for (const node of nodes)
|
|
396
|
+
if (node !== '' && (dir === '' || node.startsWith(`${dir}/`)))
|
|
397
|
+
edges.add(node);
|
|
398
|
+
}
|
|
399
|
+
edges.delete(project.path);
|
|
400
|
+
}
|
|
401
|
+
return graph;
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* The projects of `root` that changed files (paths relative to `root`) can affect: the project that holds each file (the
|
|
405
|
+
* nearest enclosing one) and every project that depends on one, however indirectly. A change to a root config file or
|
|
406
|
+
* to a file a tslaws.json extends selects every project.
|
|
407
|
+
*/
|
|
408
|
+
export function affectedProjects(root, files) {
|
|
409
|
+
const dir = resolve(root);
|
|
410
|
+
const projects = discoverProjects(dir);
|
|
411
|
+
const every = (reason) => projects.map((project) => ({ project, reason }));
|
|
412
|
+
const bases = new Map();
|
|
413
|
+
for (const project of projects)
|
|
414
|
+
for (const base of extendsChain(dir, project.dir))
|
|
415
|
+
bases.set(base, project.path === '' ? '.' : project.path);
|
|
416
|
+
for (const file of files) {
|
|
417
|
+
if (!file.includes('/') && rootConfig.test(file))
|
|
418
|
+
return every(`${file} changed (root config)`);
|
|
419
|
+
const user = bases.get(file);
|
|
420
|
+
if (user !== undefined)
|
|
421
|
+
return every(`${file} changed (extended by ${user})`);
|
|
422
|
+
}
|
|
423
|
+
const graph = dependencyGraph(dir, projects);
|
|
424
|
+
const why = new Map();
|
|
425
|
+
const direct = new Set();
|
|
426
|
+
const queue = [];
|
|
427
|
+
for (const file of files) {
|
|
428
|
+
for (let at = parentOf(file);; at = parentOf(at)) {
|
|
429
|
+
if (graph.has(at)) {
|
|
430
|
+
if (!why.has(at)) {
|
|
431
|
+
why.set(at, `contains changed file ${file}`);
|
|
432
|
+
direct.add(at);
|
|
433
|
+
queue.push(at);
|
|
434
|
+
}
|
|
435
|
+
break;
|
|
436
|
+
}
|
|
437
|
+
if (at === '')
|
|
438
|
+
break;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
const dependents = new Map();
|
|
442
|
+
for (const [node, edges] of graph)
|
|
443
|
+
for (const edge of edges)
|
|
444
|
+
dependents.set(edge, [...(dependents.get(edge) ?? []), node]);
|
|
445
|
+
for (const node of queue) {
|
|
446
|
+
for (const next of dependents.get(node) ?? []) {
|
|
447
|
+
if (why.has(next))
|
|
448
|
+
continue;
|
|
449
|
+
why.set(next, `depends on ${node === '' ? '.' : node}, which ${direct.has(node) ? 'has changes' : 'is affected'}`);
|
|
450
|
+
queue.push(next);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
return projects.flatMap((project) => {
|
|
454
|
+
const reason = why.get(project.path);
|
|
455
|
+
return reason === undefined ? [] : [{ project, reason }];
|
|
456
|
+
});
|
|
457
|
+
}
|