tslaws 0.9.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 +8 -2
- package/bin/tslaws.js +8 -2
- package/dist/browser.d.ts +1 -1
- package/dist/browser.js +36 -7
- 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 +215 -28
- package/dist/cli.d.ts +4 -0
- package/dist/cli.js +324 -41
- package/dist/compile.d.ts +17 -1
- package/dist/compile.js +244 -25
- package/dist/coverage.d.ts +55 -3
- package/dist/coverage.js +231 -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 +70 -0
- package/dist/projects.js +457 -0
- package/dist/promote.d.ts +56 -2
- package/dist/promote.js +429 -13
- package/dist/property.js +13 -2
- package/dist/propertyWorker.js +11 -1
- package/dist/proposals.d.ts +52 -4
- package/dist/proposals.js +484 -21
- package/dist/reporters.js +5 -1
- package/dist/runtimeEnv.d.ts +32 -0
- package/dist/runtimeEnv.js +146 -0
- 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/env.d.ts +17 -0
- package/hooks/claude-hook.mjs +2 -0
- package/package.json +22 -6
package/dist/projects.js
ADDED
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
// Project discovery for a monorepo: a project is a directory holding a tslaws.json. Which directories to look in comes
|
|
2
|
+
// from the first source that names any: `projects` in the root tslaws.json, `workspaces` in package.json (npm, yarn
|
|
3
|
+
// and bun alike), or `packages:` in pnpm-workspace.yaml.
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
6
|
+
import { dirname, join, relative, resolve } from 'node:path';
|
|
7
|
+
import { projectsProblem, readConfig } from "./coverage.js";
|
|
8
|
+
import { globMatcher } from "./globs.js";
|
|
9
|
+
import { customLawFile } from "./lawFiles.js";
|
|
10
|
+
import { readResolution } from "./tsconfigResolve.js";
|
|
11
|
+
/** Directories never searched, for projects or for laws files. */
|
|
12
|
+
const skipped = new Set(['node_modules', '.git', 'dist', '.tslaws']);
|
|
13
|
+
/** `./packages/a/` as `packages/a`; `.` and `./` as ''. */
|
|
14
|
+
function normalise(path) {
|
|
15
|
+
return path
|
|
16
|
+
.replaceAll('\\', '/')
|
|
17
|
+
.replace(/^(\.\/)+/, '')
|
|
18
|
+
.replace(/\/+$/, '')
|
|
19
|
+
.replace(/^\.$/, '');
|
|
20
|
+
}
|
|
21
|
+
function readJson(file) {
|
|
22
|
+
return JSON.parse(readFileSync(file, 'utf8'));
|
|
23
|
+
}
|
|
24
|
+
/** The raw `projects` list of tslaws.json in `dir`, or undefined when there is no file or no such key. */
|
|
25
|
+
function projectsOf(dir) {
|
|
26
|
+
const file = join(dir, 'tslaws.json');
|
|
27
|
+
if (!existsSync(file))
|
|
28
|
+
return undefined;
|
|
29
|
+
const raw = readJson(file);
|
|
30
|
+
if (typeof raw !== 'object' || raw === null || raw.projects === undefined)
|
|
31
|
+
return undefined;
|
|
32
|
+
const problem = projectsProblem(raw.projects);
|
|
33
|
+
if (problem !== undefined)
|
|
34
|
+
throw new Error(`tslaws.json: ${problem}`);
|
|
35
|
+
return raw.projects;
|
|
36
|
+
}
|
|
37
|
+
/** The `workspaces` globs of a package.json text (an array, or `{ packages: [...] }`); [] when absent or unparsable. */
|
|
38
|
+
export function workspacesIn(text) {
|
|
39
|
+
let workspaces;
|
|
40
|
+
try {
|
|
41
|
+
workspaces = JSON.parse(text)?.workspaces;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return [];
|
|
45
|
+
}
|
|
46
|
+
const list = Array.isArray(workspaces) ? workspaces : workspaces?.packages;
|
|
47
|
+
return Array.isArray(list) ? list.filter((entry) => typeof entry === 'string') : [];
|
|
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
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The `packages:` list of pnpm-workspace.yaml. Only the plain shapes pnpm documents are read: a block list of
|
|
64
|
+
* (optionally quoted) globs, or a one-line `[a, b]`. That keeps this free of a YAML dependency.
|
|
65
|
+
*/
|
|
66
|
+
export function pnpmPackages(text) {
|
|
67
|
+
const found = [];
|
|
68
|
+
let inList = false;
|
|
69
|
+
for (const line of text.split(/\r?\n/)) {
|
|
70
|
+
if (/^\s*(#.*)?$/.test(line))
|
|
71
|
+
continue;
|
|
72
|
+
if (/^\S/.test(line)) {
|
|
73
|
+
const key = /^packages\s*:\s*(.*?)\s*(?:#.*)?$/.exec(line);
|
|
74
|
+
inList = key !== null;
|
|
75
|
+
if (key?.[1]?.startsWith('[') === true) {
|
|
76
|
+
for (const item of key[1].replace(/^\[|\]$/g, '').split(',')) {
|
|
77
|
+
const value = item.trim().replace(/^(['"])(.*)\1$/, '$2');
|
|
78
|
+
if (value !== '')
|
|
79
|
+
found.push(value);
|
|
80
|
+
}
|
|
81
|
+
inList = false;
|
|
82
|
+
}
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (!inList)
|
|
86
|
+
continue;
|
|
87
|
+
const item = /^\s*-\s*(?:'([^']*)'|"([^"]*)"|([^#\s][^#]*?))\s*(?:#.*)?$/.exec(line);
|
|
88
|
+
const value = item?.[1] ?? item?.[2] ?? item?.[3];
|
|
89
|
+
if (value !== undefined && value !== '')
|
|
90
|
+
found.push(value);
|
|
91
|
+
}
|
|
92
|
+
return found;
|
|
93
|
+
}
|
|
94
|
+
function pnpmWorkspacesOf(dir) {
|
|
95
|
+
const file = join(dir, 'pnpm-workspace.yaml');
|
|
96
|
+
return existsSync(file) ? pnpmPackages(readFileSync(file, 'utf8')) : [];
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Whether the glob `pattern` could match `path` or something below it, from its fixed leading segments alone. It lets
|
|
100
|
+
* the search skip a whole `apps/` tree when the globs are `packages/*`.
|
|
101
|
+
*/
|
|
102
|
+
function reaches(pattern, path) {
|
|
103
|
+
const want = pattern.split('/');
|
|
104
|
+
const have = path.split('/');
|
|
105
|
+
for (const [index, segment] of have.entries()) {
|
|
106
|
+
const expected = want[index];
|
|
107
|
+
if (expected === undefined)
|
|
108
|
+
return want[want.length - 1] === '**';
|
|
109
|
+
if (/[*?]/.test(expected))
|
|
110
|
+
return true;
|
|
111
|
+
if (expected !== segment)
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
/** Directories (relative POSIX paths) under `root` that hold a tslaws.json and match `globs`. */
|
|
117
|
+
function normalisedGlobs(globs) {
|
|
118
|
+
return globs.map((glob) => {
|
|
119
|
+
const negated = glob.startsWith('!');
|
|
120
|
+
return `${negated ? '!' : ''}${normalise(negated ? glob.slice(1) : glob)}`;
|
|
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);
|
|
126
|
+
const matches = globMatcher(patterns);
|
|
127
|
+
const includes = patterns.filter((glob) => !glob.startsWith('!'));
|
|
128
|
+
const found = [];
|
|
129
|
+
const walk = (path) => {
|
|
130
|
+
const dir = path === '' ? root : join(root, path);
|
|
131
|
+
if (path !== '' && matches(path) && existsSync(join(dir, marker)))
|
|
132
|
+
found.push(path);
|
|
133
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
134
|
+
if (!entry.isDirectory() || skipped.has(entry.name))
|
|
135
|
+
continue;
|
|
136
|
+
const next = path === '' ? entry.name : `${path}/${entry.name}`;
|
|
137
|
+
if (includes.some((glob) => reaches(glob, next)))
|
|
138
|
+
walk(next);
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
walk('');
|
|
142
|
+
return found;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* The cheap test for "the root has laws of its own": a tsc-laws.lock beside it, any `*.laws.ts` file outside the
|
|
146
|
+
* projects, or a file the root's `laws` globs pick that declares a law. It reads directory names, and the contents of
|
|
147
|
+
* only those files the `laws` globs match; it skips node_modules, .git, dist and each project, and stops at the first
|
|
148
|
+
* hit.
|
|
149
|
+
*/
|
|
150
|
+
function rootHasLaws(root, projects) {
|
|
151
|
+
if (existsSync(join(root, 'tsc-laws.lock')))
|
|
152
|
+
return true;
|
|
153
|
+
const inProject = new Set(projects);
|
|
154
|
+
const custom = customLawFile(root, readConfig(root).laws);
|
|
155
|
+
const walk = (path) => {
|
|
156
|
+
for (const entry of readdirSync(path === '' ? root : join(root, path), { withFileTypes: true })) {
|
|
157
|
+
if (entry.isFile() &&
|
|
158
|
+
(entry.name.endsWith('.laws.ts') || custom(path === '' ? entry.name : `${path}/${entry.name}`)))
|
|
159
|
+
return true;
|
|
160
|
+
if (!entry.isDirectory() || skipped.has(entry.name))
|
|
161
|
+
continue;
|
|
162
|
+
const next = path === '' ? entry.name : `${path}/${entry.name}`;
|
|
163
|
+
if (!inProject.has(next) && walk(next))
|
|
164
|
+
return true;
|
|
165
|
+
}
|
|
166
|
+
return false;
|
|
167
|
+
};
|
|
168
|
+
return walk('');
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Every project under `root`, sorted by path. The root itself is one only when it has a tslaws.json and either that
|
|
172
|
+
* file has no `projects` key (a plain single project that happens to hold others) or the root carries laws of its
|
|
173
|
+
* own (see `rootHasLaws`); a root whose tslaws.json only lists projects is just the list.
|
|
174
|
+
*/
|
|
175
|
+
export function discoverProjects(root, opts = {}) {
|
|
176
|
+
const dir = resolve(root);
|
|
177
|
+
const listed = projectsOf(dir);
|
|
178
|
+
const globs = listed ?? [workspacesOf(dir), pnpmWorkspacesOf(dir)].find((list) => list.length > 0) ?? [];
|
|
179
|
+
const paths = globs.length === 0 ? [] : matchingProjects(dir, globs);
|
|
180
|
+
if (existsSync(join(dir, 'tslaws.json')) && (listed === undefined || rootHasLaws(dir, paths)))
|
|
181
|
+
paths.push('');
|
|
182
|
+
let projects = paths.sort().map((path) => ({
|
|
183
|
+
dir: path === '' ? dir : join(dir, path),
|
|
184
|
+
path,
|
|
185
|
+
standalone: path !== '' && standaloneOf(join(dir, path)),
|
|
186
|
+
}));
|
|
187
|
+
if (opts.only !== undefined && opts.only.length > 0) {
|
|
188
|
+
const only = new Set(opts.only.map(normalise));
|
|
189
|
+
projects = projects.filter((project) => only.has(project.path));
|
|
190
|
+
}
|
|
191
|
+
else if (opts.standalone !== true)
|
|
192
|
+
projects = projects.filter((project) => !project.standalone);
|
|
193
|
+
if (opts.filter !== undefined && opts.filter.length > 0) {
|
|
194
|
+
const matches = globMatcher(opts.filter.map((glob) => (glob.startsWith('!') ? `!${normalise(glob.slice(1))}` : normalise(glob))));
|
|
195
|
+
projects = projects.filter((project) => matches(project.path));
|
|
196
|
+
}
|
|
197
|
+
return projects;
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Whether `cwd` is the root of a monorepo run: it has no tslaws.json but discovery finds projects below it, or its
|
|
201
|
+
* tslaws.json has a `projects` list.
|
|
202
|
+
*/
|
|
203
|
+
export function isMonorepoRoot(cwd) {
|
|
204
|
+
const dir = resolve(cwd);
|
|
205
|
+
if (!existsSync(join(dir, 'tslaws.json')))
|
|
206
|
+
return discoverProjects(dir, { standalone: true }).length > 0;
|
|
207
|
+
return projectsOf(dir) !== undefined;
|
|
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
|
+
}
|
package/dist/promote.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import ts from 'typescript';
|
|
1
2
|
export interface ParsedLaw {
|
|
2
3
|
name: string;
|
|
3
4
|
/** The declaration as written, from `export` to its end. */
|
|
@@ -5,10 +6,27 @@ export interface ParsedLaw {
|
|
|
5
6
|
start: number;
|
|
6
7
|
end: number;
|
|
7
8
|
}
|
|
9
|
+
/** A top-level statement that is neither an import nor a law (a helper const, function, type, interface, class, enum or namespace). */
|
|
10
|
+
export interface ParsedDeclaration {
|
|
11
|
+
/** The names the statement declares: one for most, several for `const a = 1, b = 2` or a destructuring. */
|
|
12
|
+
names: string[];
|
|
13
|
+
/** The statement as written, with the comments directly above it (a JSDoc block, `//` lines) and no blank line between. */
|
|
14
|
+
text: string;
|
|
15
|
+
start: number;
|
|
16
|
+
end: number;
|
|
17
|
+
/** Every identifier the statement mentions, apart from property names after a `.`. A superset of what it really references. */
|
|
18
|
+
references: string[];
|
|
19
|
+
}
|
|
8
20
|
export interface ParsedLawFile {
|
|
9
21
|
/** Whole import statements, in order. */
|
|
10
22
|
imports: string[];
|
|
11
23
|
laws: ParsedLaw[];
|
|
24
|
+
/** Where the last import statement ends, or 0 when there is none. */
|
|
25
|
+
importEnd: number;
|
|
26
|
+
/** The named top-level statements that are not imports or laws, in source order. */
|
|
27
|
+
declarations: ParsedDeclaration[];
|
|
28
|
+
/** The text with the imports and laws overwritten by spaces (line breaks kept): what is left to the helpers and anything else. */
|
|
29
|
+
rest: string;
|
|
12
30
|
}
|
|
13
31
|
/**
|
|
14
32
|
* `foo.proposed.laws.ts` -> `foo.laws.ts`, `foo.browser.proposed.laws.ts` -> `foo.browser.laws.ts` and
|
|
@@ -21,13 +39,45 @@ export declare function acceptedPathFor(proposed: string): string | undefined;
|
|
|
21
39
|
* brackets: a law ends at its closing `}` or at a `;` at depth 0.
|
|
22
40
|
*/
|
|
23
41
|
export declare function parseLawFile(text: string): ParsedLawFile;
|
|
42
|
+
/** The identifiers in `text`, found with the scanner so it also reads a law (`export law ...`, which is not standard TypeScript). */
|
|
43
|
+
export declare function identifiersIn(text: string): Set<string>;
|
|
44
|
+
/** The code of `text` printed from its syntax tree without comments: layout is normalised, string and template contents are not. */
|
|
45
|
+
export declare function sameCode(a: string, b: string): boolean;
|
|
46
|
+
/** A `const` statement: not `let`, `var`, `using` or `await using` (the last two carry the Const flag too and call a dispose method). */
|
|
47
|
+
export declare function isPlainConst(statement: ts.VariableStatement): boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Why a helper may not be proposed or copied, or undefined when it may. A helper is a function, type or interface
|
|
50
|
+
* declaration, or a `const` whose initialiser has no side effects (a literal, a function, an object or array of those,
|
|
51
|
+
* `as const`): a helper becomes part of the accepted tree, and a `const` initialiser runs when the file loads.
|
|
52
|
+
*/
|
|
53
|
+
export declare function helperProblem(text: string): string | undefined;
|
|
54
|
+
/** Throws unless every one of `declarations` passes `helperProblem`. */
|
|
55
|
+
export declare function assertHelpersSafe(declarations: ParsedDeclaration[]): void;
|
|
56
|
+
/** Throws unless each of `imports` is exactly one import statement, so a scanning slip cannot pass other code off as an import. */
|
|
57
|
+
export declare function assertImportStatements(imports: string[]): void;
|
|
24
58
|
/** Joins the import statements, dropping repeats by whitespace-insensitive text. */
|
|
25
59
|
export declare function dedupeImports(existing: string[], added: string[]): string[];
|
|
26
60
|
/**
|
|
27
61
|
* The accepted file after promoting `laws` (with the proposed file's imports) into it. `existing` is the current text
|
|
28
|
-
* of the accepted file, or undefined when it does not exist yet.
|
|
62
|
+
* of the accepted file, or undefined when it does not exist yet. `declarations` are all the helper declarations of the
|
|
63
|
+
* proposed file: the ones the laws use, directly or through each other, are copied too. A declaration already in the
|
|
64
|
+
* accepted file with the same code (layout and comments aside) is not copied again; one of the same name with different text is
|
|
65
|
+
* an error. Throws when a law name is already taken there, and, as a safety net, when the result would use a name the
|
|
66
|
+
* proposed file declares but the accepted file does not.
|
|
29
67
|
*/
|
|
30
|
-
export declare function buildAccepted(existing: string | undefined, imports: string[], laws: ParsedLaw[]): string;
|
|
68
|
+
export declare function buildAccepted(existing: string | undefined, imports: string[], laws: ParsedLaw[], declarations?: ParsedDeclaration[]): string;
|
|
69
|
+
/** What a promote would write, with the code it adds beside the laws. */
|
|
70
|
+
export interface AcceptedPlan {
|
|
71
|
+
text: string;
|
|
72
|
+
/** The import statements the accepted file does not have yet. */
|
|
73
|
+
imports: string[];
|
|
74
|
+
/** The helper declarations copied into the accepted file. */
|
|
75
|
+
declarations: ParsedDeclaration[];
|
|
76
|
+
}
|
|
77
|
+
/** `buildAccepted`, with the imports and helpers it adds, so a person can read them before anything is written. */
|
|
78
|
+
export declare function planAccepted(existing: string | undefined, imports: string[], laws: ParsedLaw[], declarations?: ParsedDeclaration[]): AcceptedPlan;
|
|
79
|
+
/** `block` placed after the last declaration of `text`, else after its last import, else before its first law, else at the end. */
|
|
80
|
+
export declare function withDeclarations(text: string, block: string): string;
|
|
31
81
|
/** The proposed file without the promoted laws, or undefined when no law is left (the file is deleted). */
|
|
32
82
|
export declare function buildRemaining(text: string, promoted: string[]): string | undefined;
|
|
33
83
|
export interface PromoteHost {
|
|
@@ -36,6 +86,8 @@ export interface PromoteHost {
|
|
|
36
86
|
checkFile: (file: string) => Promise<Map<string, string>>;
|
|
37
87
|
ask: (question: string) => Promise<string>;
|
|
38
88
|
out: (text: string) => void;
|
|
89
|
+
/** Add the imports and helpers without asking (`--yes`); they are still printed. */
|
|
90
|
+
yes?: boolean;
|
|
39
91
|
}
|
|
40
92
|
/** Walks the proposed files, asks per law, and rewrites the accepted and proposed files. Returns the number promoted. */
|
|
41
93
|
export declare function promoteFiles(host: PromoteHost, proposedFiles: string[]): Promise<number>;
|
|
@@ -52,6 +104,8 @@ export interface PromoteProposalHost {
|
|
|
52
104
|
checkFile: (file: string) => Promise<Map<string, string>>;
|
|
53
105
|
ask: (question: string) => Promise<string>;
|
|
54
106
|
out: (text: string) => void;
|
|
107
|
+
/** Add the imports and helpers without asking (`--yes`); they are still printed. */
|
|
108
|
+
yes?: boolean;
|
|
55
109
|
}
|
|
56
110
|
export interface PromoteProposalResult {
|
|
57
111
|
/** Project-relative path the laws went to; undefined when the person declined or nothing was moved. */
|