@ref0/workspace 0.1.0 → 0.2.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 +101 -1
- package/dist/bin.mjs +95 -12
- package/dist/lint/generic/entry-reexports.mjs +1 -1
- package/dist/package-exports.mjs +157 -0
- package/dist/symbols/check.mjs +209 -0
- package/dist/symbols/find.mjs +63 -0
- package/dist/symbols/symbols.mjs +390 -0
- package/dist/type-coverage.mjs +68 -0
- package/dist/types/cache.mjs +157 -0
- package/dist/types/inputs.mjs +71 -0
- package/dist/types/projects.mjs +65 -0
- package/dist/types/types.mjs +175 -0
- package/package.json +17 -1
package/README.md
CHANGED
|
@@ -59,11 +59,111 @@ entry point's source:
|
|
|
59
59
|
repo's own `SKILL.md`s, `AGENTS.md`s, the root's `RULES.md`, and `GLOSSARY.md`. It reads the
|
|
60
60
|
Markdown Git tracks. Skills the root's `skills-lock.json` names are upstream copies; without the
|
|
61
61
|
lock there are none.
|
|
62
|
+
- `symbols find <words...>` and `symbols check <base> [<head>]` or `symbols check --all`: what the
|
|
63
|
+
repo already has, and a change that copies it, as [Symbols](#symbols) says.
|
|
64
|
+
- `types`: the types of every project the root `tsconfig.json` reaches, and Effect's rules, with
|
|
65
|
+
the repo's own `effect-tsgo tsrs`, each error once, in the project that includes its file. Each
|
|
66
|
+
project's result is kept for every checkout on the machine, in `REF0_WORKSPACE_TYPES_CACHE` or
|
|
67
|
+
`ref0-workspace-types` in the user's cache folder, and replayed while nothing it read changes.
|
|
68
|
+
- `type-coverage`: every tracked TypeScript file is in a project the root reaches, and lint reads
|
|
69
|
+
it, unless a tool writes it (`*.gen.ts`).
|
|
70
|
+
- `package-exports [--packages <glob>]... [--condition <name>]`: each package's `exports` names
|
|
71
|
+
files it tracks or its `vite.config.ts`'s `pack` builds, and each entry point that builds gives
|
|
72
|
+
its source under the condition first. `--packages` is `packages/*` and `--condition`
|
|
73
|
+
`@ref0/source` unless given.
|
|
74
|
+
|
|
75
|
+
`types` and `type-coverage` run the repo's own `@effect/tsgo`, `tsrs` and `typescript`, its
|
|
76
|
+
optional peers, resolved from its root, at the versions its catalog pins.
|
|
77
|
+
|
|
78
|
+
## Symbols
|
|
79
|
+
|
|
80
|
+
`symbols` keeps a repo from collecting copies of its own code. `find` shows what the repo already
|
|
81
|
+
has before you write it. `check` fails a change that copies a function, class or const the repo
|
|
82
|
+
already has.
|
|
83
|
+
|
|
84
|
+
Both read every top-level declaration in the repo's source files with oxc, through `parseAst` from
|
|
85
|
+
Vite+, and keep each file's declarations in `node_modules/.cache/ref0-workspace-symbols/`, one cache
|
|
86
|
+
per checkout and never committed, so a file is parsed again only when it changes. Declarations,
|
|
87
|
+
generated `*.gen.ts` files, `dist/`, `node_modules/`, `.agents/` and `.claude/` are left out.
|
|
88
|
+
|
|
89
|
+
### Find a function before you write one
|
|
90
|
+
|
|
91
|
+
```sh
|
|
92
|
+
ref0-workspace symbols find join bytes
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
It prints the ten best matches in the working tree, each with its file and line, its signature and
|
|
96
|
+
the first line of its doc comment:
|
|
97
|
+
|
|
98
|
+
```text
|
|
99
|
+
joined function src/bytes.ts:78
|
|
100
|
+
(chunks: ReadonlyArray<Uint8Array>, size: number) =>
|
|
101
|
+
Whatever the reader gave, as one run of bytes.
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
A word in the name counts most, then a word in the doc comment, then one in the signature or path.
|
|
105
|
+
A match for every word ranks higher, and test files are included but rank lower, as `best` in
|
|
106
|
+
[`find.ts`](src/symbols/find.ts) scores them.
|
|
107
|
+
|
|
108
|
+
### Check a change for copies
|
|
109
|
+
|
|
110
|
+
```sh
|
|
111
|
+
ref0-workspace symbols check origin/main
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
It compares the branch, with any changes not yet committed, against the base, and prints each copy,
|
|
115
|
+
then a count:
|
|
116
|
+
|
|
117
|
+
```text
|
|
118
|
+
copy: src/browsers.ts:90 browsedBy has the same body as openedBy at src/sessions.ts:479
|
|
119
|
+
near copy: src/loader.ts:44 storedVersion is storedCheckCode at src/code.ts:218 with other names in it
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
An exact copy fails the check. A near copy only warns. In CI, run it on a pull request's merge into
|
|
123
|
+
main, `ref0-workspace symbols check HEAD^1 HEAD`: under GitHub Actions each copy is an annotation on
|
|
124
|
+
its line in the diff.
|
|
125
|
+
|
|
126
|
+
To keep a copy on purpose, say why in a comment directly above it:
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
// CLONE: the sender's bundle takes no code from bytes.ts.
|
|
130
|
+
const concat = (chunks: ReadonlyArray<Uint8Array>) => {
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
`ref0-workspace symbols check --all` lists every copy already in the repo, but those a `// CLONE:`
|
|
134
|
+
comment allows, and always passes.
|
|
135
|
+
|
|
136
|
+
### What counts as a copy
|
|
137
|
+
|
|
138
|
+
[`check.ts`](src/symbols/check.ts) owns the comparison scope, thresholds and exclusions.
|
|
139
|
+
[`symbols.ts`](src/symbols/symbols.ts) defines the exact and loose fingerprints.
|
|
140
|
+
|
|
141
|
+
### Limits
|
|
142
|
+
|
|
143
|
+
- It compares whole top-level declarations. It doesn't find a block copied inside a function, or a
|
|
144
|
+
function nested in another.
|
|
145
|
+
- A body that has the same fingerprint as another, but calls functions that do different things,
|
|
146
|
+
is still an exact copy. Mark it with a `// CLONE:` comment.
|
|
147
|
+
- A body that's mostly one pattern repeated, such as a long list of names, is never a near copy.
|
|
148
|
+
Two such lists of the same length would look alike whatever names they hold.
|
|
149
|
+
- If a change edits two copies that already existed and they still match, the check reports them.
|
|
150
|
+
|
|
151
|
+
### Tune it
|
|
152
|
+
|
|
153
|
+
The thresholds are the constants at the top of `check.ts`: `minSize`, `nearAlike` and `commonRun`.
|
|
154
|
+
Before you change one, replay a consumer's last 30 merged pull requests from its checkout and read
|
|
155
|
+
every copy the check reports:
|
|
156
|
+
|
|
157
|
+
```sh
|
|
158
|
+
for merge in $(git log --first-parent --merges -30 --format=%h origin/main); do
|
|
159
|
+
pnpm exec ref0-workspace symbols check "$merge^1" "$merge"
|
|
160
|
+
done
|
|
161
|
+
```
|
|
62
162
|
|
|
63
163
|
## Releasing
|
|
64
164
|
|
|
65
165
|
From [ref-0/home](https://github.com/ref-0/home): bump `version` in this package's `package.json`
|
|
66
|
-
on main, a patch for a fix and a minor for a new rule, and once CI passes that commit, push the
|
|
166
|
+
on main, a patch for a fix and a minor for a new rule or check, and once CI passes that commit, push the
|
|
67
167
|
tag `workspace-v<version>` at it. `release.yml` checks that CI passed exactly that commit and
|
|
68
168
|
publishes it.
|
|
69
169
|
|
package/dist/bin.mjs
CHANGED
|
@@ -1,30 +1,113 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { docsBudget } from "./docs-budget.mjs";
|
|
3
|
+
import { defaultCondition, packageExports } from "./package-exports.mjs";
|
|
4
|
+
import { symbolsCheck } from "./symbols/check.mjs";
|
|
5
|
+
import { symbolsFind } from "./symbols/find.mjs";
|
|
6
|
+
import { typeCoverage } from "./type-coverage.mjs";
|
|
7
|
+
import { types } from "./types/types.mjs";
|
|
8
|
+
import { execFileSync } from "node:child_process";
|
|
3
9
|
import { argv, cwd, exit } from "node:process";
|
|
10
|
+
import { parseArgs } from "node:util";
|
|
4
11
|
// src/bin.ts
|
|
5
12
|
/**
|
|
6
13
|
* `ref0-workspace <check>`: the checks every ref-0 repo runs, each a subcommand, run from anywhere
|
|
7
14
|
* in the repo's checkout.
|
|
8
15
|
*
|
|
9
|
-
* ref0-workspace docs-budget
|
|
16
|
+
* ref0-workspace docs-budget the docs agents load, each within its budget
|
|
17
|
+
* ref0-workspace symbols find <words...> what the repo has, before you write it again
|
|
18
|
+
* ref0-workspace symbols check <base> [<head>] no change copies what the repo has
|
|
19
|
+
* ref0-workspace symbols check --all every copy the repo holds
|
|
20
|
+
* ref0-workspace types types and Effect's rules, every project
|
|
21
|
+
* ref0-workspace type-coverage every TypeScript file in a project, and linted
|
|
22
|
+
* ref0-workspace package-exports [--packages <glob>]... [--condition <name>]
|
|
23
|
+
* each package's exports name files it has
|
|
10
24
|
*/
|
|
11
|
-
/**
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
25
|
+
/** The root of the Git checkout the command runs in, or where it runs outside one. */
|
|
26
|
+
const root = () => {
|
|
27
|
+
try {
|
|
28
|
+
return execFileSync("git", ["rev-parse", "--show-toplevel"], {
|
|
29
|
+
cwd: cwd(),
|
|
30
|
+
encoding: "utf8",
|
|
31
|
+
stdio: [
|
|
32
|
+
"ignore",
|
|
33
|
+
"pipe",
|
|
34
|
+
"ignore"
|
|
35
|
+
]
|
|
36
|
+
}).trim();
|
|
37
|
+
} catch {
|
|
38
|
+
return cwd();
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
/** Prints the usage, and answers the exit code for a command it doesn't take. */
|
|
42
|
+
const usageError = () => {
|
|
43
|
+
console.error(usage());
|
|
44
|
+
return 2;
|
|
45
|
+
};
|
|
46
|
+
/** A check that takes no arguments, run at the checkout's root. */
|
|
47
|
+
const plain = (about, run) => ({
|
|
48
|
+
args: "",
|
|
49
|
+
about,
|
|
50
|
+
run: (args) => {
|
|
51
|
+
if (args.length > 0) return usageError();
|
|
52
|
+
return run(root());
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
const checks = /* @__PURE__ */ new Map([
|
|
56
|
+
["docs-budget", plain("the docs agents load, each within its budget", (at) => {
|
|
57
|
+
const { docs, problems } = docsBudget(at);
|
|
16
58
|
for (const line of problems) console.error(line);
|
|
17
59
|
if (problems.length > 0) return 1;
|
|
18
60
|
console.error(`docs-budget: ${docs.length} Markdown files within budget`);
|
|
19
61
|
return 0;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
|
|
62
|
+
})],
|
|
63
|
+
["symbols", {
|
|
64
|
+
args: "find <words...> | check <base> [<head>] | check --all",
|
|
65
|
+
about: "what the repo has, before you write it again, and no change copying it",
|
|
66
|
+
run: ([command, ...rest]) => {
|
|
67
|
+
if (command === "find") return symbolsFind(rest, cwd());
|
|
68
|
+
if (command === "check") return symbolsCheck(rest, cwd());
|
|
69
|
+
return usageError();
|
|
70
|
+
}
|
|
71
|
+
}],
|
|
72
|
+
["types", plain("types and Effect's rules, in every project the root reaches", types)],
|
|
73
|
+
["type-coverage", plain("every TypeScript file in a project the root reaches, and linted", typeCoverage)],
|
|
74
|
+
["package-exports", {
|
|
75
|
+
args: "[--packages <glob>]... [--condition <name>]",
|
|
76
|
+
about: "each package's exports name files it has or builds",
|
|
77
|
+
run: (args) => {
|
|
78
|
+
const parsed = (() => {
|
|
79
|
+
try {
|
|
80
|
+
return parseArgs({
|
|
81
|
+
args: [...args],
|
|
82
|
+
options: {
|
|
83
|
+
packages: {
|
|
84
|
+
type: "string",
|
|
85
|
+
multiple: true,
|
|
86
|
+
default: ["packages/*"]
|
|
87
|
+
},
|
|
88
|
+
condition: {
|
|
89
|
+
type: "string",
|
|
90
|
+
default: defaultCondition
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}).values;
|
|
94
|
+
} catch {
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
})();
|
|
98
|
+
if (parsed === void 0) return usageError();
|
|
99
|
+
return packageExports(root(), parsed);
|
|
100
|
+
}
|
|
101
|
+
}]
|
|
102
|
+
]);
|
|
103
|
+
function usage() {
|
|
104
|
+
return ["usage: ref0-workspace <check>", ...[...checks].map(([name, { args, about }]) => [` ${name}${args === "" ? "" : ` ${args}`}`, ` ${about}`].join("\n"))].join("\n");
|
|
105
|
+
}
|
|
23
106
|
const [name, ...rest] = argv.slice(2);
|
|
24
107
|
const check = name === void 0 ? void 0 : checks.get(name);
|
|
25
|
-
if (check === void 0
|
|
26
|
-
console.error(name === void 0
|
|
108
|
+
if (check === void 0) {
|
|
109
|
+
console.error(name === void 0 ? usage() : `ref0-workspace: no check ${name}\n${usage()}`);
|
|
27
110
|
exit(2);
|
|
28
111
|
}
|
|
29
|
-
exit(check.run());
|
|
112
|
+
exit(await check.run(rest));
|
|
30
113
|
export {};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
2
|
import { join, relative, resolve, sep } from "node:path";
|
|
3
|
-
import { defineRule } from "vite-plus/lint/plugins";
|
|
4
3
|
import { Schema } from "effect";
|
|
4
|
+
import { defineRule } from "vite-plus/lint/plugins";
|
|
5
5
|
// src/lint/generic/entry-reexports.ts
|
|
6
6
|
/**
|
|
7
7
|
* What the rule takes: the repo's root, as an absolute path; `entries`, the folders from the root
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { existsSync, globSync, readFileSync } from "node:fs";
|
|
3
|
+
import { join, posix } from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import { Schema } from "effect";
|
|
6
|
+
// src/package-exports.ts
|
|
7
|
+
/**
|
|
8
|
+
* Fails when a workspace package's `exports` names a file nothing has or builds, or a generated
|
|
9
|
+
* file.
|
|
10
|
+
*
|
|
11
|
+
* ref0-workspace package-exports [--packages <glob>]... [--condition <name>]
|
|
12
|
+
*
|
|
13
|
+
* It reads the `package.json` in each folder `--packages` matches, `packages/*` unless it's given,
|
|
14
|
+
* its `publishConfig.exports` too, and the `pack` of the package's `vite.config.ts`, and holds each
|
|
15
|
+
* to these:
|
|
16
|
+
*
|
|
17
|
+
* - It has an `exports` field, so no other package reaches a file it doesn't list. One nothing
|
|
18
|
+
* imports, such as a CLI's, is empty.
|
|
19
|
+
* - Each target, condition by condition, names a tracked file, or a `dist/` file one of its pack
|
|
20
|
+
* entries builds: `dist/<entry>.mjs`, and `dist/<entry>.d.mts` when it packs types. A `*`
|
|
21
|
+
* target matches at least one tracked file.
|
|
22
|
+
* - No target names a `*.gen.ts` file, which a tool writes and git ignores.
|
|
23
|
+
* - A package that packs builds each entry point that has a `types` condition from a pack entry.
|
|
24
|
+
* - Each entry point in `exports` with a `types` or `import` target gives its source, a tracked
|
|
25
|
+
* file, under the source condition first, `--condition`, `@ref0/source` unless it's given, so
|
|
26
|
+
* the workspace reads source and only the published package reads what's built.
|
|
27
|
+
* `publishConfig.exports`, what the published package exports, has none.
|
|
28
|
+
*
|
|
29
|
+
* Under 1 s.
|
|
30
|
+
*/
|
|
31
|
+
/** An entry point's target: a path, or a path for each condition. */
|
|
32
|
+
const Target = Schema.Union([Schema.String, Schema.Record(Schema.String, Schema.String)]);
|
|
33
|
+
const Exports = Schema.Record(Schema.String, Target);
|
|
34
|
+
const Manifest = Schema.Struct({
|
|
35
|
+
name: Schema.String,
|
|
36
|
+
exports: Schema.optionalKey(Exports),
|
|
37
|
+
publishConfig: Schema.optionalKey(Schema.Struct({ exports: Schema.optionalKey(Exports) }))
|
|
38
|
+
});
|
|
39
|
+
/** What the check reads of one `vp pack` build: its entries, and whether it packs types. */
|
|
40
|
+
const PackBuild = Schema.Struct({
|
|
41
|
+
entry: Schema.Union([Schema.Array(Schema.String), Schema.Record(Schema.String, Schema.String)]),
|
|
42
|
+
dts: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Struct({})]))
|
|
43
|
+
});
|
|
44
|
+
/** A `vite.config.ts` module, as far as its `pack`. */
|
|
45
|
+
const ConfigModule = Schema.Struct({ default: Schema.Struct({ pack: Schema.optionalKey(Schema.Union([PackBuild, Schema.Array(PackBuild)])) }) });
|
|
46
|
+
const decodeManifest = Schema.decodeUnknownSync(Schema.fromJsonString(Manifest));
|
|
47
|
+
const decodeConfigModule = Schema.decodeUnknownSync(ConfigModule);
|
|
48
|
+
const isPaths = Schema.is(Schema.Array(Schema.String));
|
|
49
|
+
const isBuilds = Schema.is(Schema.Array(PackBuild));
|
|
50
|
+
const isPath = Schema.is(Schema.String);
|
|
51
|
+
/** The folder every path in `paths` is in, as `vp pack` names entries below it. */
|
|
52
|
+
const commonFolder = (paths) => {
|
|
53
|
+
const [first = [], ...rest] = paths.map((path) => posix.dirname(path).split("/"));
|
|
54
|
+
let length = first.length;
|
|
55
|
+
for (const parts of rest) while (length > 0 && parts.slice(0, length).join("/") !== first.slice(0, length).join("/")) length -= 1;
|
|
56
|
+
return first.slice(0, length).join("/");
|
|
57
|
+
};
|
|
58
|
+
/** Each pack entry's output name: the object's key, or its path below the entries' folder. */
|
|
59
|
+
const entryNames = ({ entry }) => {
|
|
60
|
+
if (!isPaths(entry)) return Object.keys(entry);
|
|
61
|
+
const folder = commonFolder(entry);
|
|
62
|
+
return entry.map((path) => posix.relative(folder, path).replace(/\.[cm]?[jt]sx?$/, ""));
|
|
63
|
+
};
|
|
64
|
+
/** The `dist/` files a package's pack builds, by path from the package's folder. */
|
|
65
|
+
const builtFiles = (pack) => new Set(pack.flatMap((build) => entryNames(build).flatMap((name) => build.dts === void 0 || build.dts === false ? [`dist/${name}.mjs`] : [`dist/${name}.mjs`, `dist/${name}.d.mts`])));
|
|
66
|
+
/** Each `[condition, path]` of a target; a plain path has no condition. */
|
|
67
|
+
const paths = (target) => isPath(target) ? [[void 0, target]] : Object.entries(target);
|
|
68
|
+
/** Whether `pattern`, a target with at most one `*`, matches any of `files`. */
|
|
69
|
+
const matches = (pattern, files) => {
|
|
70
|
+
if (!pattern.includes("*")) return files.has(pattern);
|
|
71
|
+
const [before = "", after = ""] = pattern.split("*");
|
|
72
|
+
return [...files].some((file) => file.length > before.length + after.length && file.startsWith(before) && file.endsWith(after));
|
|
73
|
+
};
|
|
74
|
+
/** The source condition `problems` asks for unless it's given another. */
|
|
75
|
+
const defaultCondition = "@ref0/source";
|
|
76
|
+
/**
|
|
77
|
+
* What each package's exports break, one line each, with what to do about it. `condition` is the
|
|
78
|
+
* condition each entry point names its source under.
|
|
79
|
+
*/
|
|
80
|
+
const problems = (packages, tracked, condition = defaultCondition) => {
|
|
81
|
+
const found = [];
|
|
82
|
+
for (const { directory, manifest, pack } of packages) {
|
|
83
|
+
const at = `${directory}/package.json`;
|
|
84
|
+
const built = new Set([...builtFiles(pack)].map((path) => `${directory}/${path}`));
|
|
85
|
+
const files = /* @__PURE__ */ new Set([...tracked, ...built]);
|
|
86
|
+
if (manifest.exports === void 0) {
|
|
87
|
+
found.push(`${at}: has no exports, so any of its files can be imported. List its entry points, or write "exports": {} if nothing imports it.`);
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
const maps = [["exports", manifest.exports], ["publishConfig.exports", manifest.publishConfig?.exports ?? {}]];
|
|
91
|
+
for (const [field, exports] of maps) for (const [entry, target] of Object.entries(exports)) {
|
|
92
|
+
const name = `${field}["${entry}"]`;
|
|
93
|
+
for (const [named, path] of paths(target)) {
|
|
94
|
+
const where = named === void 0 ? name : `${name}["${named}"]`;
|
|
95
|
+
const file = posix.join(directory, path);
|
|
96
|
+
if (/\.gen\.ts$/.test(path)) {
|
|
97
|
+
found.push(`${at}: ${where} names ${path}, which a tool writes. Export the module that uses it instead.`);
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (named === condition && !matches(file, tracked) && matches(file, files)) {
|
|
101
|
+
found.push(`${at}: ${where} names ${path}, which a build writes. Point it at the source the build reads.`);
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if (matches(file, files)) continue;
|
|
105
|
+
found.push(path.startsWith("./dist/") ? `${at}: ${where} names ${path}, which no pack entry builds. Add its entry to pack in vite.config.ts, or point it at a file that's there.` : `${at}: ${where} names ${path}, which isn't tracked. Point it at a file that's there.`);
|
|
106
|
+
}
|
|
107
|
+
const types = isPath(target) ? void 0 : target["types"];
|
|
108
|
+
const packed = isPath(target) ? [] : ["types", "import"].filter((key) => key in target);
|
|
109
|
+
const first = isPath(target) ? void 0 : Object.keys(target)[0];
|
|
110
|
+
if (field === "exports" && packed.length > 0 && first !== condition) found.push(`${at}: ${name} has ${packed.join(" and ")} but not its source under "${condition}" first. Add "${condition}": its source file, ahead of ${packed.join(" and ")}.`);
|
|
111
|
+
if (pack.length > 0 && types !== void 0 && !built.has(posix.join(directory, types))) found.push(`${at}: ${name} has types at ${types}, which no pack entry builds. Add "${entry}"'s source to pack's entry in vite.config.ts.`);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return found;
|
|
115
|
+
};
|
|
116
|
+
/** The folders `patterns` match at `root` that hold a `package.json`, from the root, sorted. */
|
|
117
|
+
const packageFolders = (root, patterns) => [...new Set(patterns.flatMap((pattern) => globSync(posix.join(pattern, "package.json"), { cwd: root }).map((path) => posix.dirname(path))))].sort();
|
|
118
|
+
/** Each package in `folders`, with the pack its `vite.config.ts` sets. */
|
|
119
|
+
const readPackages = async (root, folders) => Promise.all(folders.map(async (directory) => {
|
|
120
|
+
const manifest = decodeManifest(readFileSync(join(root, directory, "package.json"), "utf8"));
|
|
121
|
+
const config = join(root, directory, "vite.config.ts");
|
|
122
|
+
if (!existsSync(config)) return {
|
|
123
|
+
directory,
|
|
124
|
+
manifest,
|
|
125
|
+
pack: []
|
|
126
|
+
};
|
|
127
|
+
const { pack } = decodeConfigModule(await import(pathToFileURL(config).href)).default;
|
|
128
|
+
return {
|
|
129
|
+
directory,
|
|
130
|
+
manifest,
|
|
131
|
+
pack: pack === void 0 ? [] : isBuilds(pack) ? pack : [pack]
|
|
132
|
+
};
|
|
133
|
+
}));
|
|
134
|
+
/** Checks the packages of the repo at `root`, prints each problem, and answers the exit code. */
|
|
135
|
+
const packageExports = async (root, { packages, condition }) => {
|
|
136
|
+
const folders = packageFolders(root, packages);
|
|
137
|
+
if (folders.length === 0) {
|
|
138
|
+
console.error(`package-exports: no package.json in ${packages.join(" or ")}. Name the packages' folders with --packages.`);
|
|
139
|
+
return 1;
|
|
140
|
+
}
|
|
141
|
+
const tracked = new Set(execFileSync("git", [
|
|
142
|
+
"ls-files",
|
|
143
|
+
"-z",
|
|
144
|
+
"--",
|
|
145
|
+
...folders
|
|
146
|
+
], {
|
|
147
|
+
cwd: root,
|
|
148
|
+
encoding: "utf8",
|
|
149
|
+
maxBuffer: 67108864
|
|
150
|
+
}).split("\0").filter((path) => path !== ""));
|
|
151
|
+
const found = problems(await readPackages(root, folders), tracked, condition);
|
|
152
|
+
for (const line of found) console.error(line);
|
|
153
|
+
if (found.length > 0) return 1;
|
|
154
|
+
console.error(`package-exports: the exports of ${folders.length} packages hold`);
|
|
155
|
+
return 0;
|
|
156
|
+
};
|
|
157
|
+
export { builtFiles, defaultCondition, packageExports, packageFolders, problems };
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { filesAt, git, indexed, likeness, repoRoot, symbolCache, workingFiles } from "./symbols.mjs";
|
|
2
|
+
import { env } from "node:process";
|
|
3
|
+
// src/symbols/check.ts
|
|
4
|
+
/**
|
|
5
|
+
* Fails when a change adds a copy of a function, class or const the repo already has, and warns
|
|
6
|
+
* when it adds a near copy.
|
|
7
|
+
*
|
|
8
|
+
* ref0-workspace symbols check <base> [<head>]
|
|
9
|
+
* ref0-workspace symbols check --all
|
|
10
|
+
*
|
|
11
|
+
* It checks the top-level declarations a change adds or changes since it left `<base>`: those in
|
|
12
|
+
* `<head>`, or in the working tree without one, whose body differs from the same name's in the
|
|
13
|
+
* same file at the merge base. It compares each with every other declaration at the head. So a
|
|
14
|
+
* function moved to another file isn't a copy, and copies already on `<base>` are left alone.
|
|
15
|
+
*
|
|
16
|
+
* An exact copy has the same fingerprint, as `symbols.ts` makes it. A near copy's looser
|
|
17
|
+
* fingerprint is at least 85% alike. A `// CLONE: <why>` comment above a declaration allows
|
|
18
|
+
* it to copy. Tests, types and bodies under 40 nodes are left out.
|
|
19
|
+
*
|
|
20
|
+
* `--all` lists every copy in the working tree, new or not, but those a CLONE comment allows,
|
|
21
|
+
* and always passes.
|
|
22
|
+
*
|
|
23
|
+
* CI runs it on a pull request's merge into main, against main.
|
|
24
|
+
*/
|
|
25
|
+
const minSize = 40;
|
|
26
|
+
const nearAlike = .85;
|
|
27
|
+
const commonRun = 64;
|
|
28
|
+
const comparable = (symbol) => !symbol.test && symbol.kind !== "type" && symbol.size >= minSize;
|
|
29
|
+
const indexOf = (all) => {
|
|
30
|
+
const symbols = all.filter(comparable);
|
|
31
|
+
const byHash = /* @__PURE__ */ new Map();
|
|
32
|
+
const byRun = /* @__PURE__ */ new Map();
|
|
33
|
+
for (const [at, symbol] of symbols.entries()) {
|
|
34
|
+
byHash.set(symbol.hash, [...byHash.get(symbol.hash) ?? [], symbol]);
|
|
35
|
+
for (const run of symbol.runs) {
|
|
36
|
+
const holders = byRun.get(run);
|
|
37
|
+
if (holders === void 0) byRun.set(run, [at]);
|
|
38
|
+
else holders.push(at);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
symbols,
|
|
43
|
+
byHash,
|
|
44
|
+
byRun
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
/** The declarations at least `nearAlike` like `target`, most alike first. */
|
|
48
|
+
const nearCopies = (target, index) => {
|
|
49
|
+
const counts = /* @__PURE__ */ new Map();
|
|
50
|
+
let common = 0;
|
|
51
|
+
for (const run of target.runs) {
|
|
52
|
+
const holders = index.byRun.get(run) ?? [];
|
|
53
|
+
if (holders.length > commonRun) {
|
|
54
|
+
common += 1;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
for (const holder of holders) counts.set(holder, (counts.get(holder) ?? 0) + 1);
|
|
58
|
+
}
|
|
59
|
+
const needed = nearAlike * target.runs.length - common;
|
|
60
|
+
return [...counts].flatMap(([at, count]) => {
|
|
61
|
+
const other = index.symbols[at];
|
|
62
|
+
if (other === void 0 || other === target || count < needed) return [];
|
|
63
|
+
const sizes = [other.runs.length, target.runs.length];
|
|
64
|
+
if (Math.min(...sizes) < nearAlike * Math.max(...sizes)) return [];
|
|
65
|
+
const alike = likeness(target.runs, other.runs);
|
|
66
|
+
return alike >= nearAlike ? [{
|
|
67
|
+
other,
|
|
68
|
+
alike
|
|
69
|
+
}] : [];
|
|
70
|
+
}).sort((a, b) => b.alike - a.alike);
|
|
71
|
+
};
|
|
72
|
+
const pairKey = (a, b) => [`${a.file}:${a.name}`, `${b.file}:${b.name}`].sort().join(" ");
|
|
73
|
+
/**
|
|
74
|
+
* The copies among `changed`: each with every declaration that has its fingerprint, or failing
|
|
75
|
+
* that, the one most like it. Each group of exact copies and each near pair is listed once, and a
|
|
76
|
+
* declaration with a CLONE comment never.
|
|
77
|
+
*/
|
|
78
|
+
const copiesIn = (symbols, changed) => {
|
|
79
|
+
const index = indexOf(symbols);
|
|
80
|
+
const listed = /* @__PURE__ */ new Set();
|
|
81
|
+
const copies = [];
|
|
82
|
+
for (const copy of changed) {
|
|
83
|
+
if (!comparable(copy) || copy.clone !== void 0) continue;
|
|
84
|
+
const same = (index.byHash.get(copy.hash) ?? []).filter((other) => other !== copy).sort((a, b) => Number(b.exported) - Number(a.exported) || a.file.localeCompare(b.file));
|
|
85
|
+
if (same.length > 0) {
|
|
86
|
+
if (!listed.has(copy.hash)) copies.push({
|
|
87
|
+
exact: true,
|
|
88
|
+
copy,
|
|
89
|
+
of: same,
|
|
90
|
+
alike: 1
|
|
91
|
+
});
|
|
92
|
+
listed.add(copy.hash);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const [nearest] = nearCopies(copy, index);
|
|
96
|
+
const pair = nearest === void 0 ? void 0 : pairKey(copy, nearest.other);
|
|
97
|
+
if (nearest === void 0 || pair === void 0 || listed.has(pair)) continue;
|
|
98
|
+
listed.add(pair);
|
|
99
|
+
copies.push({
|
|
100
|
+
exact: false,
|
|
101
|
+
copy,
|
|
102
|
+
of: [nearest.other],
|
|
103
|
+
alike: nearest.alike
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
return copies;
|
|
107
|
+
};
|
|
108
|
+
const gitText = (root, args) => git(root, args).toString("utf8");
|
|
109
|
+
const pathList = (output) => output.split("\0").filter((path) => indexed(path));
|
|
110
|
+
/** A declaration's file, name and body together, which a change to any of them changes. */
|
|
111
|
+
const versionOf = (symbol) => `${symbol.file}\0${symbol.name}\0${symbol.hash}`;
|
|
112
|
+
/**
|
|
113
|
+
* The declarations at `head`, or in the working tree without one, and those of them the change
|
|
114
|
+
* since it left `base` adds, or whose body it changes.
|
|
115
|
+
*/
|
|
116
|
+
const changedSince = (root, base, head) => {
|
|
117
|
+
const mergeBase = gitText(root, [
|
|
118
|
+
"merge-base",
|
|
119
|
+
base,
|
|
120
|
+
head ?? "HEAD"
|
|
121
|
+
]).trim();
|
|
122
|
+
const paths = new Set(head === void 0 ? [...pathList(gitText(root, [
|
|
123
|
+
"diff",
|
|
124
|
+
"--name-only",
|
|
125
|
+
"-z",
|
|
126
|
+
mergeBase
|
|
127
|
+
])), ...pathList(gitText(root, [
|
|
128
|
+
"ls-files",
|
|
129
|
+
"-z",
|
|
130
|
+
"--others",
|
|
131
|
+
"--exclude-standard"
|
|
132
|
+
]))] : pathList(gitText(root, [
|
|
133
|
+
"diff",
|
|
134
|
+
"--name-only",
|
|
135
|
+
"-z",
|
|
136
|
+
mergeBase,
|
|
137
|
+
head
|
|
138
|
+
])));
|
|
139
|
+
const cache = symbolCache(root);
|
|
140
|
+
const before = new Set(filesAt(root, mergeBase, [...paths]).flatMap(cache.symbolsOf).map(versionOf));
|
|
141
|
+
const symbols = (head === void 0 ? workingFiles(root) : filesAt(root, head)).flatMap(cache.symbolsOf);
|
|
142
|
+
const changed = symbols.filter((symbol) => paths.has(symbol.file) && !before.has(versionOf(symbol)));
|
|
143
|
+
cache.save();
|
|
144
|
+
return {
|
|
145
|
+
symbols,
|
|
146
|
+
changed
|
|
147
|
+
};
|
|
148
|
+
};
|
|
149
|
+
const where = (symbol) => `${symbol.file}:${symbol.line}`;
|
|
150
|
+
const percent = (alike) => `${Math.floor(alike * 100)}%`;
|
|
151
|
+
/** The declarations a copy copies, as `joined at a.ts:3, joined at b.ts:9 and 1 more`. */
|
|
152
|
+
const named = (symbols) => {
|
|
153
|
+
const shown = symbols.slice(0, 2).map((symbol) => `${symbol.name} at ${where(symbol)}`);
|
|
154
|
+
const more = symbols.length - shown.length;
|
|
155
|
+
return more > 0 ? `${shown.join(", ")} and ${more} more` : shown.join(" and ");
|
|
156
|
+
};
|
|
157
|
+
/** One line for a copy: a GitHub annotation on its line in CI, or plain text. */
|
|
158
|
+
const reported = (copy, github) => {
|
|
159
|
+
const original = copy.of[0]?.name ?? "";
|
|
160
|
+
const what = copy.exact ? `${copy.copy.name} has the same body as ${named(copy.of)}` : copy.alike === 1 ? `${copy.copy.name} is ${named(copy.of)} with other names in it` : `${copy.copy.name} is ${percent(copy.alike)} like ${named(copy.of)}`;
|
|
161
|
+
const advice = copy.exact ? `Reuse ${original}, or say why not in a "// CLONE: <why>" comment above ${copy.copy.name}.` : `If they do the same job, reuse ${original}.`;
|
|
162
|
+
if (!github) return `${copy.exact ? "copy" : "near copy"}: ${where(copy.copy)} ${what}`;
|
|
163
|
+
const level = copy.exact ? "error" : "warning";
|
|
164
|
+
const title = `${copy.exact ? "Copy" : "Near copy"} of ${original}`;
|
|
165
|
+
return `::${level} file=${copy.copy.file},line=${copy.copy.line},title=${title}::${what}. ${advice}`;
|
|
166
|
+
};
|
|
167
|
+
const count = (n, one, many = `${one}s`) => `${n.toLocaleString("en-US")} ${n === 1 ? one : many}`;
|
|
168
|
+
/**
|
|
169
|
+
* Every copy in the working tree but those a CLONE comment allows, largest first: the exact
|
|
170
|
+
* groups, then the near pairs.
|
|
171
|
+
*/
|
|
172
|
+
const reportAll = (root) => {
|
|
173
|
+
const cache = symbolCache(root);
|
|
174
|
+
const symbols = workingFiles(root).flatMap(cache.symbolsOf).filter((symbol) => symbol.clone === void 0);
|
|
175
|
+
cache.save();
|
|
176
|
+
const exact = [...indexOf(symbols).byHash.values()].filter((group) => group.length > 1).sort((a, b) => (b[0]?.size ?? 0) - (a[0]?.size ?? 0));
|
|
177
|
+
const near = copiesIn(symbols, symbols.filter(comparable)).filter((copy) => !copy.exact);
|
|
178
|
+
console.log(`Exact copies, ${count(exact.length, "group")}:`);
|
|
179
|
+
for (const group of exact) console.log(` ${group[0]?.size} nodes: ${group.map((s) => `${s.name} ${where(s)}`).join(", ")}`);
|
|
180
|
+
console.log(`\nNear copies, ${count(near.length, "pair")}:`);
|
|
181
|
+
for (const copy of near.sort((a, b) => b.copy.size - a.copy.size)) console.log(` ${percent(copy.alike)}: ${copy.copy.name} ${where(copy.copy)}, ${named(copy.of)}`);
|
|
182
|
+
};
|
|
183
|
+
const checkUsage = ["usage: ref0-workspace symbols check <base> [<head>]", " ref0-workspace symbols check --all"].join("\n");
|
|
184
|
+
/** Checks the repo `from` is in, as `args` ask, and answers the exit code. */
|
|
185
|
+
const symbolsCheck = (args, from) => {
|
|
186
|
+
const root = repoRoot(from);
|
|
187
|
+
const [base, head, ...rest] = args.filter((arg) => arg !== "--all");
|
|
188
|
+
if (args.includes("--all")) {
|
|
189
|
+
if (base !== void 0) {
|
|
190
|
+
console.error(checkUsage);
|
|
191
|
+
return 2;
|
|
192
|
+
}
|
|
193
|
+
reportAll(root);
|
|
194
|
+
return 0;
|
|
195
|
+
}
|
|
196
|
+
if (base === void 0 || rest.length > 0 || base.startsWith("-")) {
|
|
197
|
+
console.error(checkUsage);
|
|
198
|
+
return 2;
|
|
199
|
+
}
|
|
200
|
+
const { symbols, changed } = changedSince(root, base, head);
|
|
201
|
+
const copies = copiesIn(symbols, changed);
|
|
202
|
+
const exact = copies.filter((copy) => copy.exact).length;
|
|
203
|
+
const github = env["GITHUB_ACTIONS"] === "true";
|
|
204
|
+
for (const copy of copies) console.log(reported(copy, github));
|
|
205
|
+
if (exact > 0 && !github) console.log("Reuse the existing one, or say why not in a \"// CLONE: <why>\" comment above the copy.");
|
|
206
|
+
console.log(`symbols: ${count(changed.length, "new or changed declaration")}, of ${count(symbols.length, "declaration")} in all: ${count(exact, "copy", "copies")}, ${count(copies.length - exact, "near copy", "near copies")}`);
|
|
207
|
+
return exact > 0 ? 1 : 0;
|
|
208
|
+
};
|
|
209
|
+
export { changedSince, checkUsage, copiesIn, symbolsCheck };
|