Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

knip-schemas.ts

340 lines13.1 KB

1// @effect-diagnostics nodeBuiltinImport:off - Knip and the TypeScript compiler host use synchronous Node paths.
2import * as NodeOS from "node:os";
3import * as NodePath from "node:path";
4import * as NodeWorkerThreads from "node:worker_threads";
5import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import * as Digest from "effect/crypto/Digest";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Schema from "effect/Schema";
11import type { Preprocessor } from "knip";
12// Knip needs the legacy compiler API, which TypeScript 7 no longer exports.
13import ts from "typescript-legacy";
14​
15const schemaTypeId = "~effect/Schema/Schema";
16​
17// One tsconfig's files, each with the export names its issues mention. Only
18// those names are checked: inferring the type of every export cost seconds.
19interface Project {
20 readonly cwd: string;
21 readonly configPath: string | undefined;
22 readonly files: ReadonlyArray<readonly [string, ReadonlyArray<string>]>;
24​
25// Each tsconfig needs its own program. The programs share parsed and bound
26// files (Effect's and Node's declarations) through one registry, as the
27// language service does. Without it, building 17 programs took about 13 s.
28const registry = ts.createDocumentRegistry();
29​
30// Repo-relative with "/" on every platform.
31const repoPath = (cwd: string, file: string) =>
32 NodePath.relative(cwd, NodePath.resolve(cwd, file)).split(NodePath.sep).join("/");
33​
34// Returns each file with those of its names that are Effect schemas, and every
35// file outside node_modules that the type check loaded to decide it.
36function findSchemas({ cwd, configPath, files }: Project) {
37 const config = configPath
38 ? ts.getParsedCommandLineOfConfigFile(
39 configPath,
40 {},
41 {
42 ...ts.sys,
43 onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
44 throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
45 },
46 },
47 )
48 : undefined;
49 if (config?.errors.length) {
50 throw new Error(
51 config.errors
52 .map((error) => ts.flattenDiagnosticMessageText(error.messageText, "\n"))
53 .join("\n"),
54 );
55 }
56 const options: ts.CompilerOptions = {
57 module: ts.ModuleKind.NodeNext,
58 allowJs: true,
59 ...config?.options,
60 noEmit: true,
61 };
62 const host = ts.createCompilerHost(options);
63 const key = registry.getKeyForCompilationSettings(options);
64 host.getSourceFile = (fileName, languageVersionOrOptions) => {
65 const text = host.readFile(fileName);
66 if (text === undefined) return undefined;
67 return registry.acquireDocumentWithKey(
68 fileName,
69 ts.sys.resolvePath(fileName) as ts.Path,
70 options,
71 key,
72 ts.ScriptSnapshot.fromString(text),
73 // Files do not change during one run.
74 "1",
75 undefined,
76 languageVersionOrOptions,
77 );
78 };
79 const program = ts.createProgram(
80 files.map(([file]) => NodePath.resolve(cwd, file)),
81 options,
82 host,
83 );
84 const checker = program.getTypeChecker();
85 const sources = program
86 .getSourceFiles()
87 .map((source) => source.fileName)
88 .filter((file) => !file.includes("/node_modules/"))
89 .map((file) => repoPath(cwd, file));
90 const checked = files.flatMap(([filePath, names]) => {
91 const source = program.getSourceFile(NodePath.resolve(cwd, filePath));
92 const module = source && checker.getSymbolAtLocation(source);
93 if (!source || !module) return [];
94 const schemas = checker
95 .getExportsOfModule(module)
96 .filter((symbol) => names.includes(symbol.name))
97 .flatMap((symbol) => {
98 const exported =
99 symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
100 const target =
101 exported.flags & ts.SymbolFlags.Value
102 ? exported
103 : checker.resolveName(symbol.name, source, ts.SymbolFlags.Value, false);
104 if (!target) return [];
105 const type = checker.getTypeOfSymbolAtLocation(target, target.valueDeclaration ?? source);
106 const marker = type.getProperty(schemaTypeId);
107 if (!marker) return [];
108 const markerType = checker.getTypeOfSymbolAtLocation(marker, source);
109 return markerType.isStringLiteral() && markerType.value === schemaTypeId
110 ? [symbol.name]
111 : [];
112 });
113 return [[filePath, schemas] as const];
114 });
115 return { sources, files: checked };
117​
118// The preprocessor loads this file again as each worker.
119if (!NodeWorkerThreads.isMainThread) {
120 const projects: ReadonlyArray<Project> = NodeWorkerThreads.workerData;
121 NodeWorkerThreads.parentPort?.postMessage(projects.map(findSchemas));
123​
124// Three workers measured fastest. Each one parses Effect again, so more
125// workers cost more than they save.
126const WORKERS = Math.min(3, NodeOS.availableParallelism());
127​
128// knip-check.ts passes these; plain `knip` passes none and runs uncached.
129const PreprocessorOptions = Schema.Struct({
130 // Unused exports are reported in these workspaces only.
131 exportWorkspaces: Schema.optional(Schema.Array(Schema.String)),
132 // Where schema verdicts are kept between runs.
133 verdicts: Schema.optional(Schema.String),
134});
135const decodeOptions = Schema.decodeUnknownEffect(Schema.fromJsonString(PreprocessorOptions));
136​
137// One type check's verdicts: whether each export name it was asked about is a
138// schema, with the hash of every file it loaded. They hold while those files
139// are unchanged; knip-check.ts discards the cache when resolution, a tsconfig
140// or an installed package changes.
141const Verdicts = Schema.Array(
142 Schema.Struct({
143 sources: Schema.Record(Schema.String, Schema.String),
144 files: Schema.Record(Schema.String, Schema.Record(Schema.String, Schema.Boolean)),
145 }),
146);
147const VerdictsJson = Schema.fromJsonString(Verdicts);
148const decodeVerdicts = Schema.decodeUnknownEffect(VerdictsJson);
149const encodeVerdicts = Schema.encodeEffect(VerdictsJson);
150​
151const EXPORT_CATEGORIES = [
152 "exports",
153 "nsExports",
154 "types",
155 "nsTypes",
156 "enumMembers",
157 "namespaceMembers",
158 "duplicates",
159] as const;
160​
161const checkProjects = (
162 cwd: string,
163 projects: Map<string | undefined, Map<string, Set<string>>>,
164) => {
165 // Deal the projects out largest first so the workers get similar shares.
166 const shares = Array.from({ length: WORKERS }, (): Array<Project> => []);
167 [...projects]
168 .sort(([, a], [, b]) => b.size - a.size)
169 .forEach(([configPath, files], index) => {
170 shares[index % WORKERS]!.push({
171 cwd,
172 configPath,
173 files: [...files].map(([file, names]) => [file, [...names]]),
174 });
175 });
176 const workers = shares
177 .filter((share) => share.length > 0)
178 .map((share) => new NodeWorkerThreads.Worker(new URL(import.meta.url), { workerData: share }));
179 return Promise.all(
180 workers.map(
181 (worker) =>
182 new Promise<Array<ReturnType<typeof findSchemas>>>((resolve, reject) => {
183 worker.once("message", resolve);
184 worker.once("error", reject);
185 worker.once("exit", (code) => {
186 if (code !== 0) reject(new Error(`knip-schemas worker exited with code ${code}`));
187 });
188 }),
189 ),
190 )
191 .then((results) => results.flat())
192 .catch(async (error: unknown) => {
193 // knip only sets an exit code on a failed preprocessor, so stop the
194 // siblings or the failed run waits for their work.
195 await Promise.allSettled(workers.map((worker) => worker.terminate()));
196 throw error;
197 });
198};
199​
200// Drops unused-export issues whose every symbol is an Effect schema.
201const dropSchemas = Effect.fn("knipSchemas.dropSchemas")(function* (
202 options: Parameters<Preprocessor>[0],
203) {
204 const fs = yield* FileSystem.FileSystem;
205 const digest = yield* Digest.Digest;
206 const { exportWorkspaces, verdicts: verdictsPath } = options.preprocessorOptions
207 ? yield* decodeOptions(options.preprocessorOptions)
208 : {};
209​
210 if (exportWorkspaces) {
211 for (const category of EXPORT_CATEGORIES) {
212 for (const [filePath, issues] of Object.entries(options.issues[category])) {
213 const file = repoPath(options.cwd, filePath);
214 if (exportWorkspaces.some((dir) => file.startsWith(`${dir}/`))) continue;
215 options.counters[category] -= Object.keys(issues).length;
216 delete options.issues[category][filePath];
217 }
218 }
219 }
220​
221 const categories = ["exports", "nsExports", "duplicates"] as const;
222 const projects = new Map<string | undefined, Map<string, Set<string>>>();
223 for (const category of categories) {
224 for (const [filePath, issues] of Object.entries(options.issues[category])) {
225 if (Object.keys(issues).length === 0) continue;
226 const configPath = ts.findConfigFile(
227 NodePath.dirname(NodePath.resolve(options.cwd, filePath)),
228 ts.sys.fileExists,
229 );
230 const files = projects.get(configPath) ?? new Map<string, Set<string>>();
231 const names = files.get(filePath) ?? new Set<string>();
232 for (const issue of Object.values(issues)) {
233 for (const { symbol } of issue.symbols ?? [{ symbol: issue.symbol }]) names.add(symbol);
234 }
235 files.set(filePath, names);
236 projects.set(configPath, files);
237 }
238 }
239​
240 const hashes = new Map<string, string>();
241 const hashAll = (files: ReadonlyArray<string>) =>
242 Effect.forEach(
243 [...new Set(files)].filter((file) => !hashes.has(file)),
244 (file) =>
245 fs.readFile(NodePath.resolve(options.cwd, file)).pipe(
246 Effect.flatMap((bytes) => digest.digestHex(Digest.sha256, bytes)),
247 Effect.orElseSucceed(() => "missing"),
248 Effect.map((hash) => hashes.set(file, hash)),
249 ),
250 { concurrency: 32, discard: true },
251 );
252​
253 // An unreadable or malformed cache is the same as none.
254 const stored = verdictsPath
255 ? yield* fs.readFileString(verdictsPath).pipe(
256 Effect.flatMap(decodeVerdicts),
257 Effect.orElseSucceed(() => []),
258 )
259 : [];
260 yield* hashAll(stored.flatMap((verdict) => Object.keys(verdict.sources)));
261 const kept = stored
262 .filter((verdict) =>
263 Object.entries(verdict.sources).every(([file, hash]) => hashes.get(file) === hash),
264 )
265 .map((verdict) => ({ sources: verdict.sources, files: { ...verdict.files } }));
266​
267 const schemas: Array<readonly [string, ReadonlyArray<string>]> = [];
268 for (const [configPath, files] of projects) {
269 for (const [filePath, names] of files) {
270 const key = repoPath(options.cwd, filePath);
271 const known = kept.find(
272 (verdict) =>
273 Object.hasOwn(verdict.files, key) &&
274 [...names].every((name) => Object.hasOwn(verdict.files[key]!, name)),
275 )?.files[key];
276 if (!known) continue;
277 schemas.push([filePath, [...names].filter((name) => known[name])]);
278 files.delete(filePath);
279 }
280 if (files.size === 0) projects.delete(configPath);
281 }
282​
283 if (projects.size > 0) {
284 const asked = new Map([...projects.values()].flatMap((files) => [...files]));
285 const results = yield* Effect.promise(() => checkProjects(options.cwd, projects));
286 yield* hashAll(results.flatMap((result) => result.sources));
287 for (const result of results) {
288 schemas.push(...result.files);
289 const files: Record<string, Record<string, boolean>> = {};
290 for (const [filePath, found] of result.files) {
291 const key = repoPath(options.cwd, filePath);
292 // The new verdict replaces whatever an older check recorded for this file.
293 for (const verdict of kept) delete verdict.files[key];
294 const names = [...(asked.get(filePath) ?? [])];
295 files[key] = Object.fromEntries(names.map((name) => [name, found.includes(name)]));
296 }
297 kept.push({
298 sources: Object.fromEntries(result.sources.map((file) => [file, hashes.get(file)!])),
299 files,
300 });
301 }
302 }
303 if (verdictsPath && (projects.size > 0 || kept.length !== stored.length)) {
304 // Renamed into place so a concurrent run never reads half a file. The
305 // cache only saves time, so failing to write it must not fail the check.
306 yield* Effect.gen(function* () {
307 const directory = NodePath.dirname(verdictsPath);
308 yield* fs.makeDirectory(directory, { recursive: true });
309 const temp = NodePath.join(yield* fs.makeTempDirectoryScoped({ directory }), "schemas.json");
310 yield* fs.writeFileString(
311 temp,
312 yield* encodeVerdicts(kept.filter((verdict) => Object.keys(verdict.files).length > 0)),
313 );
314 yield* fs.rename(temp, verdictsPath);
315 }).pipe(Effect.scoped, Effect.ignore);
316 }
317​
318 for (const [filePath, names] of schemas) {
319 for (const category of categories) {
320 const issues = options.issues[category][filePath];
321 if (!issues) continue;
322 for (const [key, issue] of Object.entries(issues)) {
323 const symbols = issue.symbols ?? [{ symbol: issue.symbol }];
324 if (symbols.length > 0 && symbols.every(({ symbol }) => names.includes(symbol))) {
325 delete issues[key];
326 options.counters[category]--;
327 }
328 }
329 if (Object.keys(issues).length === 0) delete options.issues[category][filePath];
330 }
331 }
332 return options;
333});
334​
335const preprocess = (options: Parameters<Preprocessor>[0]) =>
336 Effect.runPromise(
337 dropSchemas(options).pipe(Effect.provide([NodeServices.layer, NodeCrypto.layer])),
338 );
339​
340export default preprocess;