@ref0/workspace 0.9.0 → 0.11.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 +171 -2
- package/dist/bin.mjs +25 -5
- package/dist/comment-budget.mjs +161 -0
- package/dist/lint/generic/comments.mjs +53 -0
- package/dist/lint/generic/folder-imports.mjs +84 -0
- package/dist/lint/generic/folder-layers.d.mts +40 -0
- package/dist/lint/generic/folder-layers.mjs +82 -0
- package/dist/lint/generic/imports.mjs +34 -0
- package/dist/lint/generic/no-comments.mjs +79 -0
- package/dist/lint/generic/package-graph.d.mts +36 -0
- package/dist/lint/generic/package-graph.mjs +111 -0
- package/dist/lint/generic/package-imports.mjs +85 -0
- package/dist/lint/generic/plugin.d.mts +4 -2
- package/dist/lint/generic/plugin.mjs +10 -2
- package/dist/lint/generic/rule-options.mjs +17 -0
- package/dist/lint/generic/workspace-packages.d.mts +29 -0
- package/dist/lint/generic/workspace-packages.mjs +78 -0
- package/dist/lint/graph.d.mts +4 -0
- package/dist/lint/graph.mjs +3 -0
- package/dist/review-record/command.mjs +107 -0
- package/dist/review-record/index.d.mts +3 -0
- package/dist/review-record/index.mjs +3 -0
- package/dist/review-record/review-record.d.mts +33 -0
- package/dist/review-record/review-record.mjs +1253 -0
- package/dist/review-record/settings.d.mts +39 -0
- package/dist/review-record/settings.mjs +100 -0
- package/dist/symbols/symbols.mjs +1 -1
- package/package.json +9 -1
package/README.md
CHANGED
|
@@ -41,8 +41,9 @@ Each copied plugin keeps its licence and its `UPSTREAM.md`, which records its so
|
|
|
41
41
|
changes, beside its code, in the package too.
|
|
42
42
|
|
|
43
43
|
`ref0-generic`'s rules: `seeded-properties`, `index-barrel-only` and `export-type-side-effects`,
|
|
44
|
-
which `base.lint` turns on, and `effect-encoding`, `log-messages`, `env-at-entrypoints
|
|
45
|
-
`entry-reexports`, which a repo turns on for
|
|
44
|
+
which `base.lint` turns on, and `effect-encoding`, `log-messages`, `env-at-entrypoints`,
|
|
45
|
+
`entry-reexports`, `no-comments`, `package-imports` and `folder-imports`, which a repo turns on for
|
|
46
|
+
its own files. `entry-reexports` takes the repo's root,
|
|
46
47
|
the folders of the packages whose entry files it checks, and the export condition that names an
|
|
47
48
|
entry point's source:
|
|
48
49
|
|
|
@@ -53,6 +54,56 @@ entry point's source:
|
|
|
53
54
|
],
|
|
54
55
|
```
|
|
55
56
|
|
|
57
|
+
`no-comments` bans every comment but a doc comment on a declaration, a `SAFETY:` note and a tool's
|
|
58
|
+
directive. Files older than the rule keep the banned comments they had, as a budget that only
|
|
59
|
+
shrinks: a JSON file of each file's path from the root and how many it may hold, which
|
|
60
|
+
`comment-budget` writes. It takes the repo's root and the budget file's path from it, and a repo
|
|
61
|
+
with no budget file yet gives every file none. Turn it on over the repo's files, with an override
|
|
62
|
+
that leaves out what it doesn't own, such as vendored code:
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
{
|
|
66
|
+
files: ['**'],
|
|
67
|
+
excludeFiles: ['vendor/**'],
|
|
68
|
+
rules: {
|
|
69
|
+
'ref0-generic/no-comments': ['error', { root, budget: 'lint/comment-budget.json' }],
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
and add `"comments": "ref0-workspace comment-budget"` to the root `package.json`'s scripts.
|
|
75
|
+
|
|
76
|
+
`package-imports` holds each package and app to a declared graph: what it imports of each other
|
|
77
|
+
package, by entry point, and how, as `values`, `types` (only `import type`) or `tests`. Nothing
|
|
78
|
+
imports an app, a relative path never leaves a package, and a package never imports itself by name
|
|
79
|
+
outside its tests. It takes the root, globs of the folders that hold packages and apps, the graph,
|
|
80
|
+
and `nodeFiles`, the files of a package that run only in Node and take values where it takes types.
|
|
81
|
+
`folder-imports` holds each layered source folder: a file imports its own place and places below
|
|
82
|
+
it, never beside or above. A source may name `exceptions`, by file and module, which fail once no
|
|
83
|
+
import needs them; `features`, places nothing outside them imports; and `entries`, when its top
|
|
84
|
+
files are entry points, `reexports` or `code`. `@ref0/workspace/lint/graph` exports the types to
|
|
85
|
+
declare both with, and `graphProblems`, which a repo's test expects to return none:
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
import type { FolderLayers, PackageGraph } from '@ref0/workspace/lint/graph';
|
|
89
|
+
|
|
90
|
+
export const packageGraph = {
|
|
91
|
+
'@acme/ui': {},
|
|
92
|
+
'@acme/site': { '@acme/ui': { values: ['.', 'cast'], tests: ['testing'] } },
|
|
93
|
+
} as const satisfies PackageGraph<'@acme/ui' | '@acme/site', '@acme/ui'>;
|
|
94
|
+
|
|
95
|
+
export const folderLayers = {
|
|
96
|
+
'packages/ui/src': { layers: [['tokens'], ['components'], ['blocks']], entries: 'reexports' },
|
|
97
|
+
} as const satisfies FolderLayers;
|
|
98
|
+
|
|
99
|
+
// In the config's overrides:
|
|
100
|
+
'ref0-generic/package-imports': [
|
|
101
|
+
'error',
|
|
102
|
+
{ root, packages: ['packages/*'], apps: ['apps/*'], graph: packageGraph },
|
|
103
|
+
],
|
|
104
|
+
'ref0-generic/folder-imports': ['error', { root, sources: folderLayers }],
|
|
105
|
+
```
|
|
106
|
+
|
|
56
107
|
## Checks
|
|
57
108
|
|
|
58
109
|
`ref0-workspace <check>`, from anywhere in the repo's checkout:
|
|
@@ -62,8 +113,19 @@ entry point's source:
|
|
|
62
113
|
Markdown Git tracks. A `SKILL.md` fails past 6 KB and warns past 5 KB, each naming its largest
|
|
63
114
|
sections to move to `references/`. Upstream copies are the skills the root's `skills-lock.json`
|
|
64
115
|
names, and each skill with an `.agents/skills/<name>-UPSTREAM.md`.
|
|
116
|
+
- `comment-budget [--write | --grant <path>...]`: each file's banned comments, as
|
|
117
|
+
`ref0-generic/no-comments` counts them, against its budget. It reads the repo's lint config,
|
|
118
|
+
through its own Vite+, for the files the rule runs on and its options, so it needs the rule on
|
|
119
|
+
with one budget. Bare, it names each file over budget, counts what a full sweep would shed, and
|
|
120
|
+
fails when one is over. `--write` lowers each budget to what its file holds, never raising one,
|
|
121
|
+
and drops each file gone or with none left. `--grant <path>...` sets the budget of each file
|
|
122
|
+
under the paths, `.` for all, to what it holds: for a file that moved, the only way a budget
|
|
123
|
+
grows, so a review sees it.
|
|
65
124
|
- `symbols find <words...>` and `symbols check <base> [<head>]` or `symbols check --all`: what the
|
|
66
125
|
repo already has, and a change that copies it, as [Symbols](#symbols) says.
|
|
126
|
+
- `review-record [--count | --tier | --check <comment> [<body>] | --benched]`: whether a pull
|
|
127
|
+
request's review is on record for its merge risk, in CI, and a branch's floor before it opens, as
|
|
128
|
+
[The review gate](#the-review-gate) says.
|
|
67
129
|
- `types`: the types of every project the root `tsconfig.json` reaches, and Effect's rules, with
|
|
68
130
|
the repo's own `effect-tsgo tsrs`, each error once, in the project that includes its file. Each
|
|
69
131
|
project's result is kept for every checkout on the machine, in `REF0_WORKSPACE_TYPES_CACHE` or
|
|
@@ -134,6 +196,113 @@ that never installed the repo's hooks. A job that force-pushes a
|
|
|
134
196
|
`types` and `type-coverage` run the repo's own `@effect/tsgo`, `tsrs` and `typescript`, its
|
|
135
197
|
optional peers, resolved from its root, at the versions its catalog pins.
|
|
136
198
|
|
|
199
|
+
## The review gate
|
|
200
|
+
|
|
201
|
+
`ref0-workspace review-record` is the step of CI's result job that fails a pull request whose
|
|
202
|
+
review isn't on record for its merge risk, as the `review` skill's `references/merge-risk.md` and
|
|
203
|
+
the repo's `.agents/repo/review.md` say. Its body names a tier on a `Merge risk:` line, at or above
|
|
204
|
+
its floor, the highest tier its changed lines, the always-review list and its test code give it,
|
|
205
|
+
and the gate checks the session comment or `Break:` lines that tier needs.
|
|
206
|
+
|
|
207
|
+
- Bare, in CI: judges pull request `PR` of `GITHUB_REPOSITORY`, from `BASE` to `HEAD`, reading
|
|
208
|
+
GitHub with `gh` and `GH_TOKEN`, and the history from the Git checkout it runs in, which holds
|
|
209
|
+
both commits whole, blobs aside. It prints each reason it fails as an Actions `::error::`.
|
|
210
|
+
- `--count`: the branch's net lines of production source since its merge base with `origin/main`,
|
|
211
|
+
and on stderr whether that's a large change and its floor.
|
|
212
|
+
- `--tier`: the branch's floor, and what sets it, as a `Merge risk:` line.
|
|
213
|
+
- `--check <comment-file> [<body-file>]`: CI's checks on a session comment and a body, before you
|
|
214
|
+
post them.
|
|
215
|
+
- `--benched`: ci-bench's cases, one a line, that pull request `PR`'s files tie to, from the bench
|
|
216
|
+
list in the checkout it runs in.
|
|
217
|
+
|
|
218
|
+
Each reads the repo's settings, `.agents/repo/review.json`, and its always-review list,
|
|
219
|
+
`.agents/repo/review-paths.txt`, at the base: CI's from GitHub at `BASE`, and the branch
|
|
220
|
+
subcommands' at `origin/main`'s tip. A pull request's own copies count only once it merges.
|
|
221
|
+
Every key of `review.json` may be left out, for the value in brackets, which ref-0/git's gate
|
|
222
|
+
began with, and the file holds no other:
|
|
223
|
+
|
|
224
|
+
| Key | What it holds |
|
|
225
|
+
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
226
|
+
| `reviewTypes` | The review types a session may name, in lowercase, as the `review` skill's `references/types.md` lists them (its 14) |
|
|
227
|
+
| `consideredTypes` | The types each session names, as run or as not run with why, on a change a review covers: each one of `reviewTypes` (stress test, system design, red team, storage, program design, formal verification, fuzzing and fidelity) |
|
|
228
|
+
| `lowTierLines` | Changed lines, additions and deletions since the merge base, up to which a pull request may be low (150) |
|
|
229
|
+
| `highTierLines` | Changed lines up to which it may be medium, at least `lowTierLines` (500) |
|
|
230
|
+
| `productionSource` | Production source, as globs, whose net lines count toward a large change, less test code and fixtures (`packages/*/src/*.ts`, `packages/*/src/*.tsx`, `apps/*/src/*.ts`, `apps/*/src/*.tsx`) |
|
|
231
|
+
| `testCode` | Test code, as globs in `review-paths.txt`'s form (`*.test.ts`, `*.test-d.ts`, `*/testing/*`) |
|
|
232
|
+
| `testHelpers` | Shared test helpers, test code too whether `testCode` names them or not, whose change puts a pull request at medium (`*/testing/*`) |
|
|
233
|
+
| `benchedPaths` | The bench list's path, whose `<case> <glob>` lines tie source to the bench cases that time it (none: no bench) |
|
|
234
|
+
| `benchRuns` | Files under a `testing/` folder that a bench case runs all the same (none) |
|
|
235
|
+
|
|
236
|
+
```json
|
|
237
|
+
{ "benchedPaths": "bench/benched-paths.txt", "lowTierLines": 200 }
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
A file that doesn't read, a key it doesn't know, or a considered type the repo doesn't accept
|
|
241
|
+
stops the gate, which fails closed.
|
|
242
|
+
|
|
243
|
+
CI runs the command at the version the base's `pnpm-workspace.yaml` catalog names, from an npm
|
|
244
|
+
install of that version with no peers, which loads no peer, in a blobless clone of the base and
|
|
245
|
+
the head, so a pull request can't change the gate that judges it:
|
|
246
|
+
|
|
247
|
+
```yaml
|
|
248
|
+
- name: Fetch review-record history
|
|
249
|
+
id: fetch
|
|
250
|
+
if: always() && github.event_name == 'pull_request'
|
|
251
|
+
timeout-minutes: 2
|
|
252
|
+
env:
|
|
253
|
+
BASE: ${{ github.event.pull_request.base.sha }}
|
|
254
|
+
GH_TOKEN: ${{ github.token }}
|
|
255
|
+
GIT_TERMINAL_PROMPT: '0'
|
|
256
|
+
run: |
|
|
257
|
+
set -eu
|
|
258
|
+
rm -rf review-record
|
|
259
|
+
git init -q review-record
|
|
260
|
+
git -C review-record remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git"
|
|
261
|
+
git -C review-record \
|
|
262
|
+
-c credential.helper= \
|
|
263
|
+
-c 'credential.helper=!gh auth git-credential' \
|
|
264
|
+
-c credential.interactive=never \
|
|
265
|
+
fetch -q --no-tags --filter=blob:none origin "$GITHUB_SHA" "$BASE"
|
|
266
|
+
gate=$(git -C review-record ls-tree --name-only "$BASE" -- .agents/repo/review.json)
|
|
267
|
+
if [ -z "$gate" ]; then
|
|
268
|
+
echo "::notice::The base, $BASE, has no .agents/repo/review.json, so no review gate judges this pull request."
|
|
269
|
+
echo 'gate=none' >> "$GITHUB_OUTPUT"
|
|
270
|
+
exit 0
|
|
271
|
+
fi
|
|
272
|
+
git -C review-record \
|
|
273
|
+
-c credential.helper= \
|
|
274
|
+
-c 'credential.helper=!gh auth git-credential' \
|
|
275
|
+
-c credential.interactive=never \
|
|
276
|
+
checkout -q "$BASE" -- pnpm-workspace.yaml
|
|
277
|
+
version=$(sed -n "s/^ '@ref0\/workspace': \([0-9][0-9A-Za-z.+-]*\)$/\1/p" review-record/pnpm-workspace.yaml)
|
|
278
|
+
case "$version" in
|
|
279
|
+
'' | *[!0-9A-Za-z.+-]*) echo "::error::The base's catalog names no one @ref0/workspace version." >&2; exit 1 ;;
|
|
280
|
+
esac
|
|
281
|
+
npm install --prefix "$RUNNER_TEMP/review-record" --no-save --no-package-lock --omit=peer \
|
|
282
|
+
--omit=optional --ignore-scripts --no-audit --no-fund "@ref0/workspace@$version"
|
|
283
|
+
echo 'gate=base' >> "$GITHUB_OUTPUT"
|
|
284
|
+
- name: The review is on record
|
|
285
|
+
if: always() && github.event_name == 'pull_request' && steps.fetch.outcome == 'success' && steps.fetch.outputs.gate == 'base'
|
|
286
|
+
working-directory: review-record
|
|
287
|
+
env:
|
|
288
|
+
BASE: ${{ github.event.pull_request.base.sha }}
|
|
289
|
+
GH_TOKEN: ${{ github.token }}
|
|
290
|
+
HEAD: ${{ github.event.pull_request.head.sha }}
|
|
291
|
+
PR: ${{ github.event.pull_request.number }}
|
|
292
|
+
run: node "$RUNNER_TEMP/review-record/node_modules/@ref0/workspace/dist/bin.mjs" review-record
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
The job's token reads the pull request, its comments and the repo's contents. The fetch's
|
|
296
|
+
credential helper reads `GH_TOKEN` from the environment, so the token is never in `.git/config` or
|
|
297
|
+
on a command line, and a blob the gate reads later is fetched the same way, failing closed when the
|
|
298
|
+
fetch does. A base with no `review.json` holds no gate yet, and the job says so. A repo's
|
|
299
|
+
`review-paths.txt` lists `review.json`, `pnpm-workspace.yaml` and `.github/workflows/ci.yml` at
|
|
300
|
+
high, since each changes the gate the next pull request meets.
|
|
301
|
+
|
|
302
|
+
`@ref0/workspace/review-record` exports what a repo's own code reuses of the gate: `testsOnly` and
|
|
303
|
+
`benchedCases`, which a bench's seeds and its list's tests read, and `settingsFrom` and
|
|
304
|
+
`settingsPath`, to read the settings they take.
|
|
305
|
+
|
|
137
306
|
## Symbols
|
|
138
307
|
|
|
139
308
|
`symbols` keeps a repo from collecting copies of its own code. `find` shows what the repo already
|
package/dist/bin.mjs
CHANGED
|
@@ -5,8 +5,7 @@ import { docsBudget } from "./docs-budget.mjs";
|
|
|
5
5
|
import { defaultCondition, packageExports } from "./package-exports.mjs";
|
|
6
6
|
import { preCommit } from "./pre-commit.mjs";
|
|
7
7
|
import { prePush } from "./pre-push.mjs";
|
|
8
|
-
import {
|
|
9
|
-
import { symbolsFind } from "./symbols/find.mjs";
|
|
8
|
+
import { reviewRecord } from "./review-record/command.mjs";
|
|
10
9
|
import { typeCoverage } from "./type-coverage.mjs";
|
|
11
10
|
import { types } from "./types/types.mjs";
|
|
12
11
|
import { execFileSync } from "node:child_process";
|
|
@@ -19,6 +18,8 @@ import { parseArgs } from "node:util";
|
|
|
19
18
|
* in the repo's checkout.
|
|
20
19
|
*
|
|
21
20
|
* ref0-workspace docs-budget the docs agents load, each within its budget
|
|
21
|
+
* ref0-workspace comment-budget [--write | --grant <path>...]
|
|
22
|
+
* each file's banned comments, within its budget
|
|
22
23
|
* ref0-workspace symbols find <words...> what the repo has, before you write it again
|
|
23
24
|
* ref0-workspace symbols check <base> [<head>] no change copies what the repo has
|
|
24
25
|
* ref0-workspace symbols check --all every copy the repo holds
|
|
@@ -35,6 +36,12 @@ import { parseArgs } from "node:util";
|
|
|
35
36
|
* ref0-workspace pre-push <remote> <url> Git's pre-push hook: no force-push or delete
|
|
36
37
|
* of main, deploy/* or release/*, then the
|
|
37
38
|
* repo's checks
|
|
39
|
+
* ref0-workspace review-record [--count | --tier | --check <comment> [<body>] | --benched]
|
|
40
|
+
* a pull request's review is on record for its
|
|
41
|
+
* merge risk
|
|
42
|
+
*
|
|
43
|
+
* A check that needs a peer, Vite+ or a type checker, imports its module when it runs, so
|
|
44
|
+
* `review-record`, which CI runs from an install with no peers, loads none of them.
|
|
38
45
|
*/
|
|
39
46
|
/** The root of the Git checkout the command runs in, or where it runs outside one. */
|
|
40
47
|
const root = () => {
|
|
@@ -75,12 +82,20 @@ const checks = /* @__PURE__ */ new Map([
|
|
|
75
82
|
console.error(`docs-budget: ${docs.length} Markdown files within budget`);
|
|
76
83
|
return 0;
|
|
77
84
|
})],
|
|
85
|
+
["comment-budget", {
|
|
86
|
+
args: "[--write | --grant <path>...]",
|
|
87
|
+
about: "each file's banned comments, within its budget for ref0-generic/no-comments; --write lowers each budget to what its file holds, and --grant sets the budgets of the files under the paths to what each holds",
|
|
88
|
+
run: async (args) => {
|
|
89
|
+
const { commentBudget } = await import("./comment-budget.mjs");
|
|
90
|
+
return commentBudget(args, root());
|
|
91
|
+
}
|
|
92
|
+
}],
|
|
78
93
|
["symbols", {
|
|
79
94
|
args: "find <words...> | check <base> [<head>] | check --all",
|
|
80
95
|
about: "what the repo has, before you write it again, and no change copying it",
|
|
81
|
-
run: ([command, ...rest]) => {
|
|
82
|
-
if (command === "find") return symbolsFind(rest, cwd());
|
|
83
|
-
if (command === "check") return symbolsCheck(rest, cwd());
|
|
96
|
+
run: async ([command, ...rest]) => {
|
|
97
|
+
if (command === "find") return (await import("./symbols/find.mjs")).symbolsFind(rest, cwd());
|
|
98
|
+
if (command === "check") return (await import("./symbols/check.mjs")).symbolsCheck(rest, cwd());
|
|
84
99
|
return usageError();
|
|
85
100
|
}
|
|
86
101
|
}],
|
|
@@ -132,6 +147,11 @@ const checks = /* @__PURE__ */ new Map([
|
|
|
132
147
|
if (remote === void 0 || url === void 0 || extra.length > 0) return usageError();
|
|
133
148
|
return prePush(root(), url, readFileSync(0, "utf8"), env);
|
|
134
149
|
}
|
|
150
|
+
}],
|
|
151
|
+
["review-record", {
|
|
152
|
+
args: "[--count | --tier | --check <comment> [<body>] | --benched]",
|
|
153
|
+
about: "CI: a pull request's review is on record for its merge risk; --count, --tier and --check ask it of this branch, and --benched lists ci-bench's cases",
|
|
154
|
+
run: (args) => reviewRecord(args, root(), env)
|
|
135
155
|
}]
|
|
136
156
|
]);
|
|
137
157
|
function usage() {
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { decodeBudget, docTargetsVisitor, kindOf } from "./lint/generic/comments.mjs";
|
|
2
|
+
import { vitePlusAt } from "./types/projects.mjs";
|
|
3
|
+
import { execFile } from "node:child_process";
|
|
4
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { execPath } from "node:process";
|
|
6
|
+
import { promisify } from "node:util";
|
|
7
|
+
import { join, matchesGlob, relative, sep } from "node:path";
|
|
8
|
+
import { Schema } from "effect";
|
|
9
|
+
import { Visitor, parseSync } from "vite-plus";
|
|
10
|
+
// src/comment-budget.ts
|
|
11
|
+
/**
|
|
12
|
+
* Counts each file's banned comments, as `ref0-generic/no-comments` sees them, against its budget,
|
|
13
|
+
* and lowers or grants budgets.
|
|
14
|
+
*
|
|
15
|
+
* ref0-workspace comment-budget each file over budget, and what a sweep would shed
|
|
16
|
+
* ref0-workspace comment-budget --write lowers each budget to what the file holds
|
|
17
|
+
* ref0-workspace comment-budget --grant <path>... sets the budget of each file under the paths
|
|
18
|
+
* to what it holds
|
|
19
|
+
*
|
|
20
|
+
* It reads the repo's lint config, through its own Vite+, for the files the rule runs on and its
|
|
21
|
+
* options: the root and the budget file. `--write` never raises a budget, and drops a file that
|
|
22
|
+
* holds none or is gone. `--grant` raises one, for a file that moved, which keeps its comments
|
|
23
|
+
* under a path the budget doesn't know, and is the only way a budget grows, so a review sees it.
|
|
24
|
+
*/
|
|
25
|
+
const run = promisify(execFile);
|
|
26
|
+
const rule = "ref0-generic/no-comments";
|
|
27
|
+
/** The rule's options, as a repo's config sets them. */
|
|
28
|
+
const Options = Schema.Struct({
|
|
29
|
+
root: Schema.String,
|
|
30
|
+
budget: Schema.String
|
|
31
|
+
});
|
|
32
|
+
/** A rule's setting as Oxlint prints it: a severity, alone or with its options. */
|
|
33
|
+
const Setting = Schema.Union([Schema.String, Schema.Array(Schema.Unknown)]);
|
|
34
|
+
const Rules = Schema.NullOr(Schema.Record(Schema.String, Setting));
|
|
35
|
+
/** What the command reads of `vp lint --print-config`: the rules, and each override's. */
|
|
36
|
+
const decodePrinted = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Struct({
|
|
37
|
+
rules: Rules,
|
|
38
|
+
overrides: Schema.NullOr(Schema.Array(Schema.Struct({
|
|
39
|
+
files: Schema.Array(Schema.String),
|
|
40
|
+
excludeFiles: Schema.optionalKey(Schema.NullOr(Schema.Array(Schema.String))),
|
|
41
|
+
rules: Rules
|
|
42
|
+
})))
|
|
43
|
+
})));
|
|
44
|
+
const decodeOptions = Schema.decodeUnknownSync(Options);
|
|
45
|
+
const isSeverity = Schema.is(Schema.String);
|
|
46
|
+
const off = /* @__PURE__ */ new Set(["off", "allow"]);
|
|
47
|
+
/** The rule's options where `rules` turns it on, `false` where they turn it off, or nothing. */
|
|
48
|
+
const settingIn = (rules) => {
|
|
49
|
+
const setting = rules?.[rule];
|
|
50
|
+
if (setting === void 0) return void 0;
|
|
51
|
+
const [severity, options] = isSeverity(setting) ? [setting] : setting;
|
|
52
|
+
return isSeverity(severity) && off.has(severity) ? false : decodeOptions(options);
|
|
53
|
+
};
|
|
54
|
+
/** A part of a path that starts with a dot, such as `.agents`, with the dot as a letter no glob skips. */
|
|
55
|
+
const shown = (text) => text.replace(/(^|\/)\./gu, "$1");
|
|
56
|
+
/**
|
|
57
|
+
* Whether `glob` takes `path` as an override's does: `*` never crosses a `/`, as `matchesGlob`'s
|
|
58
|
+
* doesn't, but `*` and `**` match a part that starts with a dot, as Oxlint's do and `matchesGlob`'s
|
|
59
|
+
* don't, so `**` reaches `.agents/hooks/`.
|
|
60
|
+
*/
|
|
61
|
+
const matches = (path, glob) => matchesGlob(shown(path), shown(glob));
|
|
62
|
+
/**
|
|
63
|
+
* Where the rule runs in the printed config: a file's options, or nothing when it's off there. A
|
|
64
|
+
* later override wins over an earlier one and over the top-level rules, as Oxlint applies them.
|
|
65
|
+
*/
|
|
66
|
+
const ruleAt = (printed) => (path) => {
|
|
67
|
+
const setting = (printed.overrides ?? []).reduce((current, { files, excludeFiles, rules }) => files.some((glob) => matches(path, glob)) && !(excludeFiles ?? []).some((glob) => matches(path, glob)) ? settingIn(rules) ?? current : current, settingIn(printed.rules));
|
|
68
|
+
return setting === false ? void 0 : setting;
|
|
69
|
+
};
|
|
70
|
+
/** The banned comments in `text`, the file at `path`, and how many lines they take. */
|
|
71
|
+
const bannedIn = (path, text) => {
|
|
72
|
+
const { program, comments } = parseSync(path, text);
|
|
73
|
+
const targets = /* @__PURE__ */ new Set();
|
|
74
|
+
new Visitor(docTargetsVisitor((start) => targets.add(start))).visit(program);
|
|
75
|
+
const first = program.body[0];
|
|
76
|
+
if (first !== void 0) targets.add(first.start);
|
|
77
|
+
const banned = comments.filter((comment) => comment.type !== "Shebang" && kindOf(comment, text, targets) === "banned");
|
|
78
|
+
const lines = banned.reduce((sum, comment) => sum + text.slice(comment.start, comment.end).split("\n").length, 0);
|
|
79
|
+
return {
|
|
80
|
+
count: banned.length,
|
|
81
|
+
lines
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
/** Each budget lowered to what its file holds, dropping each file gone or with none. */
|
|
85
|
+
const lowered = (budget, counts) => Object.fromEntries([...counts].map(([path, count]) => [path, Math.min(count, budget[path] ?? 0)]));
|
|
86
|
+
/** Each file under `prefixes`, `.` for every file, with what it holds as its budget. */
|
|
87
|
+
const granted = (counts, prefixes) => Object.fromEntries([...counts].filter(([path]) => prefixes.some((prefix) => prefix === "." || path === prefix || path.startsWith(`${prefix.replace(/\/$/, "")}/`))));
|
|
88
|
+
/** The budget as its file holds it: sorted by path, each file with none left out. */
|
|
89
|
+
const budgetText = (budget) => `${JSON.stringify(Object.fromEntries(Object.entries(budget).filter(([, count]) => count > 0).sort(([a], [b]) => a < b ? -1 : 1)), null, 2)}\n`;
|
|
90
|
+
/** Runs the repo's own `vp lint` at `root` with `args`, and answers what it prints. */
|
|
91
|
+
const lint = async (root, args) => (await run(execPath, [
|
|
92
|
+
vitePlusAt(root),
|
|
93
|
+
"lint",
|
|
94
|
+
...args
|
|
95
|
+
], {
|
|
96
|
+
cwd: root,
|
|
97
|
+
encoding: "utf8",
|
|
98
|
+
maxBuffer: 67108864
|
|
99
|
+
})).stdout;
|
|
100
|
+
/** The command, in the repo at `root`, with its arguments; answers its exit code. */
|
|
101
|
+
const commentBudget = async (args, root) => {
|
|
102
|
+
const [mode, ...paths] = args;
|
|
103
|
+
if (mode !== void 0 && mode !== "--write" && mode !== "--grant") {
|
|
104
|
+
console.error(`comment-budget: unknown flag ${mode}. Run it bare, with --write, or with --grant <path>...`);
|
|
105
|
+
return 2;
|
|
106
|
+
}
|
|
107
|
+
if (mode !== "--grant" && paths.length > 0) {
|
|
108
|
+
console.error(`comment-budget: ${mode ?? "a bare run"} takes no paths.`);
|
|
109
|
+
return 2;
|
|
110
|
+
}
|
|
111
|
+
if (mode === "--grant" && paths.length === 0) {
|
|
112
|
+
console.error("comment-budget: --grant takes the paths whose files keep their comments.");
|
|
113
|
+
return 2;
|
|
114
|
+
}
|
|
115
|
+
const [printed, listed] = await Promise.all([lint(root, ["--print-config"]).then(decodePrinted), lint(root, ["--debug=files"])]);
|
|
116
|
+
const optionsAt = ruleAt(printed);
|
|
117
|
+
const scoped = listed.split("\n").filter((path) => path !== "" && /\.[cm]?[jt]sx?$/.test(path)).flatMap((path) => {
|
|
118
|
+
const options = optionsAt(path);
|
|
119
|
+
return options === void 0 ? [] : [{
|
|
120
|
+
path,
|
|
121
|
+
options
|
|
122
|
+
}];
|
|
123
|
+
});
|
|
124
|
+
const settings = new Set(scoped.map(({ options }) => JSON.stringify(options)));
|
|
125
|
+
const options = scoped[0]?.options;
|
|
126
|
+
if (options === void 0 || settings.size !== 1) {
|
|
127
|
+
console.error(settings.size === 0 ? `comment-budget: lint runs ${rule} on no file. Turn it on in vite.config.ts, with the repo's root and its budget file.` : `comment-budget: ${rule} runs with ${settings.size} sets of options, and the command reads one budget.`);
|
|
128
|
+
return 2;
|
|
129
|
+
}
|
|
130
|
+
const budgetFile = join(options.root, options.budget);
|
|
131
|
+
const budget = existsSync(budgetFile) ? decodeBudget(readFileSync(budgetFile, "utf8")) : {};
|
|
132
|
+
const found = new Map(scoped.map(({ path }) => [relative(options.root, join(root, path)).split(sep).join("/"), bannedIn(path, readFileSync(join(root, path), "utf8"))]));
|
|
133
|
+
const counts = new Map([...found].map(([path, { count }]) => [path, count]));
|
|
134
|
+
if (mode === "--write") {
|
|
135
|
+
writeFileSync(budgetFile, budgetText(lowered(budget, counts)));
|
|
136
|
+
return 0;
|
|
137
|
+
}
|
|
138
|
+
if (mode === "--grant") {
|
|
139
|
+
const grants = granted(counts, paths);
|
|
140
|
+
writeFileSync(budgetFile, budgetText({
|
|
141
|
+
...budget,
|
|
142
|
+
...grants
|
|
143
|
+
}));
|
|
144
|
+
console.log(`comment-budget: granted ${Object.values(grants).filter((count) => count > 0).length} files their comments.`);
|
|
145
|
+
return 0;
|
|
146
|
+
}
|
|
147
|
+
const over = [...counts].filter(([path, count]) => count > (budget[path] ?? 0));
|
|
148
|
+
const loose = [...counts].filter(([path, count]) => count < (budget[path] ?? 0));
|
|
149
|
+
const totals = [...found.values()].reduce((sum, { count, lines }) => ({
|
|
150
|
+
count: sum.count + count,
|
|
151
|
+
lines: sum.lines + lines
|
|
152
|
+
}), {
|
|
153
|
+
count: 0,
|
|
154
|
+
lines: 0
|
|
155
|
+
});
|
|
156
|
+
for (const [path, count] of over) console.log(`over ${path}: ${count} of ${budget[path] ?? 0}`);
|
|
157
|
+
console.log(`comment-budget: ${totals.count} banned comments in ${[...counts.values()].filter((count) => count > 0).length} files, ${totals.lines} lines a full sweep would shed.`);
|
|
158
|
+
if (loose.length > 0) console.log(`comment-budget: ${loose.length} budgets are above what their files hold: run --write to lower them.`);
|
|
159
|
+
return over.length > 0 ? 1 : 0;
|
|
160
|
+
};
|
|
161
|
+
export { bannedIn, budgetText, commentBudget, granted, lowered, matches, ruleAt };
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
// src/lint/generic/comments.ts
|
|
3
|
+
/** A comment a tool reads: a lint or type-check switch, a test environment, or a bundler hint. */
|
|
4
|
+
const directive = /^\s*(?:(?:eslint|oxlint)(?:-disable|-enable|-env)?\b|@ts-(?:expect-error|ignore|nocheck|check)\b|@effect-diagnostics|@vitest-environment|@vite-ignore|@jsx|prettier-ignore|oxfmt-ignore|biome-ignore|(?:c8|v8|istanbul) ignore|webpack[A-Z]|[#@]__[A-Z_]+__|\/\s*<reference\b)/;
|
|
5
|
+
/** The anti-slop rule's own test for a justification, with its default marker. */
|
|
6
|
+
const safety = /(?:^|[^\p{L}\p{N}_])SAFETY\s*:\s*\S/u;
|
|
7
|
+
/**
|
|
8
|
+
* Each node a doc comment may sit on: a declaration, an export, a class or interface member, an
|
|
9
|
+
* enum member and an object's property. A comment just before one documents it to editors and
|
|
10
|
+
* agents, which read it on hover and in declaration files.
|
|
11
|
+
*/
|
|
12
|
+
const documented = [
|
|
13
|
+
"AccessorProperty",
|
|
14
|
+
"ClassDeclaration",
|
|
15
|
+
"ExportDefaultDeclaration",
|
|
16
|
+
"ExportNamedDeclaration",
|
|
17
|
+
"FunctionDeclaration",
|
|
18
|
+
"MethodDefinition",
|
|
19
|
+
"Property",
|
|
20
|
+
"PropertyDefinition",
|
|
21
|
+
"TSAbstractAccessorProperty",
|
|
22
|
+
"TSAbstractMethodDefinition",
|
|
23
|
+
"TSAbstractPropertyDefinition",
|
|
24
|
+
"TSCallSignatureDeclaration",
|
|
25
|
+
"TSConstructSignatureDeclaration",
|
|
26
|
+
"TSDeclareFunction",
|
|
27
|
+
"TSEnumDeclaration",
|
|
28
|
+
"TSEnumMember",
|
|
29
|
+
"TSIndexSignature",
|
|
30
|
+
"TSInterfaceDeclaration",
|
|
31
|
+
"TSMethodSignature",
|
|
32
|
+
"TSModuleDeclaration",
|
|
33
|
+
"TSPropertySignature",
|
|
34
|
+
"TSTypeAliasDeclaration",
|
|
35
|
+
"VariableDeclaration"
|
|
36
|
+
];
|
|
37
|
+
/**
|
|
38
|
+
* A visitor that hands `add` where each node a doc comment may sit on starts. It visits Oxlint's
|
|
39
|
+
* tree in a rule and oxc's from `parseSync`, so each node is only its start. The caller adds where
|
|
40
|
+
* the file's first statement starts, whose doc comment is the module's.
|
|
41
|
+
*/
|
|
42
|
+
const docTargetsVisitor = (add) => Object.fromEntries(documented.map((type) => [type, (node) => add(node.start)]));
|
|
43
|
+
/** What `comment` is in `text`, given where each node a doc comment may sit on starts. */
|
|
44
|
+
const kindOf = (comment, text, targets) => {
|
|
45
|
+
if (comment.type === "Shebang" || directive.test(comment.value)) return "directive";
|
|
46
|
+
if (safety.test(comment.value)) return "safety";
|
|
47
|
+
if (comment.type !== "Block" || !comment.value.startsWith("*")) return "banned";
|
|
48
|
+
const next = text.slice(comment.end).search(/\S/);
|
|
49
|
+
return next !== -1 && targets.has(comment.end + next) ? "doc" : "banned";
|
|
50
|
+
};
|
|
51
|
+
/** Each file's budget of banned comments, by its path from the repo's root, as its budget file holds it. */
|
|
52
|
+
const decodeBudget = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Record(Schema.String, Schema.Number)));
|
|
53
|
+
export { decodeBudget, docTargetsVisitor, kindOf };
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { folderImportsOf, layerProblem, moduleNamed } from "./folder-layers.mjs";
|
|
2
|
+
import { importsVisitor } from "./imports.mjs";
|
|
3
|
+
import { testFile } from "./package-graph.mjs";
|
|
4
|
+
import { decodedOnce } from "./rule-options.mjs";
|
|
5
|
+
import { fromRoot } from "./workspace-packages.mjs";
|
|
6
|
+
import { resolve } from "node:path";
|
|
7
|
+
import { defineRule } from "vite-plus/lint/plugins";
|
|
8
|
+
// src/lint/generic/folder-imports.ts
|
|
9
|
+
const optionsOf = decodedOnce(folderImportsOf);
|
|
10
|
+
/** Whether a statement of an entry file re-exports: `export { … } from`, or `export *`. */
|
|
11
|
+
const reexports = (statement) => statement.type === "ExportNamedDeclaration" && statement.source !== null || statement.type === "ExportAllDeclaration";
|
|
12
|
+
const folderImportsRule = defineRule({
|
|
13
|
+
meta: {
|
|
14
|
+
messages: {
|
|
15
|
+
above: "{{from}} sits below {{to}} in the folder layers, so it imports nothing of it. Move what it needs down, to where both can import it.",
|
|
16
|
+
beside: "{{from}} and {{to}} sit in one layer of the folder layers, so neither imports the other. Move what it needs down, or join the two from a place above both.",
|
|
17
|
+
feature: "{{to}} is a feature a host can leave out, so {{from}} imports nothing of it. Read it through a seam {{from}} declares.",
|
|
18
|
+
entry: "{{to}} is an entry point, above every place of the folder layers, so {{from}} imports nothing of it. Import the module it re-exports.",
|
|
19
|
+
reexportOnly: "This file is an entry point at the top of its source, so it only re-exports: move this into a place of the folder layers, and re-export it here.",
|
|
20
|
+
unplaced: "{{place}} is in no layer of the folder layers. Add it to the layer it belongs in.",
|
|
21
|
+
stale: "The folder layers' exceptions let this file import {{module}}, and no import here needs that. Delete the exception."
|
|
22
|
+
},
|
|
23
|
+
schema: [{
|
|
24
|
+
type: "object",
|
|
25
|
+
properties: {
|
|
26
|
+
root: { type: "string" },
|
|
27
|
+
sources: { type: "object" }
|
|
28
|
+
},
|
|
29
|
+
required: ["root", "sources"],
|
|
30
|
+
additionalProperties: false
|
|
31
|
+
}]
|
|
32
|
+
},
|
|
33
|
+
create(context) {
|
|
34
|
+
const { root, sources } = optionsOf(context.options);
|
|
35
|
+
const path = fromRoot(root, resolve(context.filename));
|
|
36
|
+
const holding = sources.filter(({ folder }) => path.startsWith(`${folder}/`));
|
|
37
|
+
if (holding.length === 0 || testFile.test(path)) return {};
|
|
38
|
+
const used = /* @__PURE__ */ new Set();
|
|
39
|
+
const imports = importsVisitor((node, imported) => {
|
|
40
|
+
if (!imported.startsWith(".")) return;
|
|
41
|
+
const target = fromRoot(root, resolve(context.filename, "..", imported.replace(/\?.*$/, "")));
|
|
42
|
+
for (const source of holding) {
|
|
43
|
+
if (!target.startsWith(`${source.folder}/`)) continue;
|
|
44
|
+
const file = path.slice(source.folder.length + 1);
|
|
45
|
+
const module = moduleNamed(target.slice(source.folder.length + 1));
|
|
46
|
+
const problem = layerProblem(source, file, module);
|
|
47
|
+
if (problem === void 0) continue;
|
|
48
|
+
if (problem.messageId !== "unplaced" && source.exceptions?.[file]?.includes(module)) {
|
|
49
|
+
used.add(`${source.folder}\0${module}`);
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
context.report({
|
|
53
|
+
node,
|
|
54
|
+
...problem
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
const checkProgram = (program) => {
|
|
59
|
+
for (const source of holding) {
|
|
60
|
+
const file = path.slice(source.folder.length + 1);
|
|
61
|
+
if (source.entries !== "reexports" || moduleNamed(file).includes("/")) continue;
|
|
62
|
+
for (const statement of program.body) if (!reexports(statement)) context.report({
|
|
63
|
+
node: statement,
|
|
64
|
+
messageId: "reexportOnly"
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
return {
|
|
69
|
+
...imports,
|
|
70
|
+
Program: checkProgram,
|
|
71
|
+
"Program:exit"(program) {
|
|
72
|
+
for (const source of holding) {
|
|
73
|
+
const file = path.slice(source.folder.length + 1);
|
|
74
|
+
for (const module of source.exceptions?.[file] ?? []) if (!used.has(`${source.folder}\0${module}`)) context.report({
|
|
75
|
+
node: program,
|
|
76
|
+
messageId: "stale",
|
|
77
|
+
data: { module }
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
export { folderImportsRule };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How one source folder's places stack. A place is a folder of the source, a folder inside one,
|
|
3
|
+
* such as `protocol/bytes`, or a file at its top, named without its extension. A file imports any
|
|
4
|
+
* module of its own place, and of any place in a layer below its own: never one beside it, or
|
|
5
|
+
* above.
|
|
6
|
+
*/
|
|
7
|
+
export interface SourceLayers {
|
|
8
|
+
/** The source's places, layer by layer, from the bottom. */
|
|
9
|
+
readonly layers: ReadonlyArray<ReadonlyArray<string>>;
|
|
10
|
+
/**
|
|
11
|
+
* Imports allowed against the layers and the features, by the file that makes each, from the
|
|
12
|
+
* source, to the modules it imports, without their extensions. An entry no import needs fails,
|
|
13
|
+
* so the list only shrinks.
|
|
14
|
+
*/
|
|
15
|
+
readonly exceptions?: {
|
|
16
|
+
readonly [file: string]: ReadonlyArray<string>;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Places a host can leave out. No other place imports one, wherever it sits, but a file in a
|
|
20
|
+
* `testing/` folder, which builds whole hosts.
|
|
21
|
+
*/
|
|
22
|
+
readonly features?: ReadonlyArray<string>;
|
|
23
|
+
/**
|
|
24
|
+
* When the files at the top of the source are its entry points, above every place: each imports
|
|
25
|
+
* anything, and nothing imports one. `reexports` holds each to re-exports, as a package's are;
|
|
26
|
+
* `code` lets each hold code, as an app's server does. Left out, the top files are places.
|
|
27
|
+
*/
|
|
28
|
+
readonly entries?: 'reexports' | 'code';
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Each layered source folder, from the root, such as `packages/cli/src`, to its layers. A source
|
|
32
|
+
* may sit in a place of another, such as `packages/cli/src/harness`, and a file is held to every
|
|
33
|
+
* source it's in. `Source` lets a repo hold the keys to its own, as `satisfies FolderLayers<…>`.
|
|
34
|
+
*/
|
|
35
|
+
export type FolderLayers<Source extends string = string> = { readonly [Name in Source]: SourceLayers; };
|
|
36
|
+
/** What `ref0-generic/folder-imports` takes: the repo's root, as an absolute path, and its sources. */
|
|
37
|
+
export interface FolderImportsOptions {
|
|
38
|
+
readonly root: string;
|
|
39
|
+
readonly sources: FolderLayers;
|
|
40
|
+
}
|