@shivaedev/quality 0.43.0 → 0.44.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.
Files changed (151) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +55 -39
  3. package/biome/declarations.json +1 -1
  4. package/biome/preset.json +60 -60
  5. package/dist/adapters/knip/configuration.d.ts +29 -0
  6. package/dist/adapters/knip/configuration.d.ts.map +1 -0
  7. package/dist/adapters/knip/configuration.js +56 -0
  8. package/dist/adapters/knip/configuration.js.map +1 -0
  9. package/dist/adapters/knip/entryPointFindings.d.ts +3 -0
  10. package/dist/adapters/knip/entryPointFindings.d.ts.map +1 -0
  11. package/dist/adapters/knip/entryPointFindings.js +49 -0
  12. package/dist/adapters/knip/entryPointFindings.js.map +1 -0
  13. package/dist/adapters/knip/findings.d.ts +4 -0
  14. package/dist/adapters/knip/findings.d.ts.map +1 -0
  15. package/dist/adapters/knip/findings.js +40 -0
  16. package/dist/adapters/knip/findings.js.map +1 -0
  17. package/dist/adapters/knip/run.d.ts +3 -0
  18. package/dist/adapters/knip/run.d.ts.map +1 -0
  19. package/dist/adapters/knip/run.js +46 -0
  20. package/dist/adapters/knip/run.js.map +1 -0
  21. package/dist/adapters/knip/sourceConfig.d.ts +4 -0
  22. package/dist/adapters/knip/sourceConfig.d.ts.map +1 -0
  23. package/dist/adapters/knip/sourceConfig.js +15 -0
  24. package/dist/adapters/knip/sourceConfig.js.map +1 -0
  25. package/dist/biome/recognizeDiagnostics.js +2 -2
  26. package/dist/biome/recognizeDiagnostics.js.map +1 -1
  27. package/dist/docs/documentedImports.d.ts +12 -0
  28. package/dist/docs/documentedImports.d.ts.map +1 -0
  29. package/dist/docs/documentedImports.js +80 -0
  30. package/dist/docs/documentedImports.js.map +1 -0
  31. package/dist/docs/documentedModule.d.ts +11 -0
  32. package/dist/docs/documentedModule.d.ts.map +1 -0
  33. package/dist/docs/documentedModule.js +32 -0
  34. package/dist/docs/documentedModule.js.map +1 -0
  35. package/dist/docs/exportsName.d.ts +2 -0
  36. package/dist/docs/exportsName.d.ts.map +1 -0
  37. package/dist/docs/exportsName.js +25 -0
  38. package/dist/docs/exportsName.js.map +1 -0
  39. package/dist/docs/headingAnchors.d.ts +4 -0
  40. package/dist/docs/headingAnchors.d.ts.map +1 -0
  41. package/dist/docs/headingAnchors.js +43 -0
  42. package/dist/docs/headingAnchors.js.map +1 -0
  43. package/dist/docs/importFindings.d.ts +12 -0
  44. package/dist/docs/importFindings.d.ts.map +1 -0
  45. package/dist/docs/importFindings.js +36 -0
  46. package/dist/docs/importFindings.js.map +1 -0
  47. package/dist/docs/isDocument.d.ts +2 -0
  48. package/dist/docs/isDocument.d.ts.map +1 -0
  49. package/dist/docs/isDocument.js +6 -0
  50. package/dist/docs/isDocument.js.map +1 -0
  51. package/dist/docs/linkFindings.d.ts +12 -0
  52. package/dist/docs/linkFindings.d.ts.map +1 -0
  53. package/dist/docs/linkFindings.js +59 -0
  54. package/dist/docs/linkFindings.js.map +1 -0
  55. package/dist/docs/markdownLines.d.ts +11 -0
  56. package/dist/docs/markdownLines.d.ts.map +1 -0
  57. package/dist/docs/markdownLines.js +38 -0
  58. package/dist/docs/markdownLines.js.map +1 -0
  59. package/dist/docs/markdownLinks.d.ts +7 -0
  60. package/dist/docs/markdownLinks.d.ts.map +1 -0
  61. package/dist/docs/markdownLinks.js +23 -0
  62. package/dist/docs/markdownLinks.js.map +1 -0
  63. package/dist/docs/repositoryLink.d.ts +11 -0
  64. package/dist/docs/repositoryLink.d.ts.map +1 -0
  65. package/dist/docs/repositoryLink.js +28 -0
  66. package/dist/docs/repositoryLink.js.map +1 -0
  67. package/dist/imports/fences/compilePolicy.d.ts.map +1 -1
  68. package/dist/imports/fences/compilePolicy.js +1 -1
  69. package/dist/imports/fences/compilePolicy.js.map +1 -1
  70. package/dist/imports/fences/match.d.ts +1 -1
  71. package/dist/imports/fences/match.d.ts.map +1 -1
  72. package/dist/imports/fences/match.js +1 -1
  73. package/dist/imports/fences/match.js.map +1 -1
  74. package/dist/imports/packageExports.d.ts +1 -0
  75. package/dist/imports/packageExports.d.ts.map +1 -1
  76. package/dist/imports/packageExports.js +7 -5
  77. package/dist/imports/packageExports.js.map +1 -1
  78. package/dist/imports/packageName.d.ts +4 -0
  79. package/dist/imports/packageName.d.ts.map +1 -0
  80. package/dist/imports/packageName.js +25 -0
  81. package/dist/imports/packageName.js.map +1 -0
  82. package/dist/imports/resolve.d.ts +0 -2
  83. package/dist/imports/resolve.d.ts.map +1 -1
  84. package/dist/imports/resolve.js +1 -24
  85. package/dist/imports/resolve.js.map +1 -1
  86. package/dist/inventory/collect.d.ts +0 -1
  87. package/dist/inventory/collect.d.ts.map +1 -1
  88. package/dist/inventory/collect.js +1 -4
  89. package/dist/inventory/collect.js.map +1 -1
  90. package/dist/inventory/linesOf.d.ts +2 -0
  91. package/dist/inventory/linesOf.d.ts.map +1 -0
  92. package/dist/inventory/linesOf.js +5 -0
  93. package/dist/inventory/linesOf.js.map +1 -0
  94. package/dist/rules/builtIn.d.ts +2 -2
  95. package/dist/rules/builtIn.d.ts.map +1 -1
  96. package/dist/rules/builtIn.js +6 -0
  97. package/dist/rules/builtIn.js.map +1 -1
  98. package/dist/rules/docs/references.d.ts +2 -0
  99. package/dist/rules/docs/references.d.ts.map +1 -0
  100. package/dist/rules/docs/references.js +66 -0
  101. package/dist/rules/docs/references.js.map +1 -0
  102. package/dist/rules/docs/unversionedInstalls.d.ts +2 -0
  103. package/dist/rules/docs/unversionedInstalls.d.ts.map +1 -0
  104. package/dist/rules/docs/unversionedInstalls.js +36 -0
  105. package/dist/rules/docs/unversionedInstalls.js.map +1 -0
  106. package/dist/rules/files/folderNames.js +2 -2
  107. package/dist/rules/files/folderNames.js.map +1 -1
  108. package/dist/rules/imports/manifest.js +1 -1
  109. package/dist/rules/imports/manifest.js.map +1 -1
  110. package/dist/rules/imports/runtime.js +1 -1
  111. package/dist/rules/imports/runtime.js.map +1 -1
  112. package/dist/rules/stories/unitTests.js +1 -1
  113. package/dist/rules/stories/unitTests.js.map +1 -1
  114. package/dist/rules/unusedCode.d.ts +2 -0
  115. package/dist/rules/unusedCode.d.ts.map +1 -0
  116. package/dist/rules/unusedCode.js +9 -0
  117. package/dist/rules/unusedCode.js.map +1 -0
  118. package/docs/debt-and-hooks.md +0 -1
  119. package/docs/north-star.md +1 -1
  120. package/package.json +3 -2
  121. package/src/adapters/knip/configuration.ts +66 -0
  122. package/src/adapters/knip/entryPointFindings.ts +54 -0
  123. package/src/adapters/knip/findings.ts +46 -0
  124. package/src/adapters/knip/run.ts +60 -0
  125. package/src/adapters/knip/sourceConfig.ts +20 -0
  126. package/src/biome/recognizeDiagnostics.ts +2 -2
  127. package/src/docs/documentedImports.ts +104 -0
  128. package/src/docs/documentedModule.ts +44 -0
  129. package/src/docs/exportsName.ts +27 -0
  130. package/src/docs/headingAnchors.ts +52 -0
  131. package/src/docs/importFindings.ts +62 -0
  132. package/src/docs/isDocument.ts +6 -0
  133. package/src/docs/linkFindings.ts +90 -0
  134. package/src/docs/markdownLines.ts +56 -0
  135. package/src/docs/markdownLinks.ts +33 -0
  136. package/src/docs/repositoryLink.ts +44 -0
  137. package/src/imports/fences/compilePolicy.ts +2 -1
  138. package/src/imports/fences/match.ts +2 -1
  139. package/src/imports/packageExports.ts +8 -5
  140. package/src/imports/packageName.ts +31 -0
  141. package/src/imports/resolve.ts +1 -31
  142. package/src/inventory/collect.ts +1 -5
  143. package/src/inventory/linesOf.ts +4 -0
  144. package/src/rules/builtIn.ts +6 -0
  145. package/src/rules/docs/references.ts +83 -0
  146. package/src/rules/docs/unversionedInstalls.ts +53 -0
  147. package/src/rules/files/folderNames.ts +2 -2
  148. package/src/rules/imports/manifest.ts +1 -1
  149. package/src/rules/imports/runtime.ts +1 -1
  150. package/src/rules/stories/unitTests.ts +1 -1
  151. package/src/rules/unusedCode.ts +10 -0
@@ -0,0 +1,46 @@
1
+ import { Schema } from "effect";
2
+ import type { Finding } from "#rule.ts";
3
+
4
+ const ReportSymbol = Schema.Struct({ line: Schema.optional(Schema.Number), name: Schema.String });
5
+ const Issue = Schema.Struct({
6
+ dependencies: Schema.optional(Schema.Array(ReportSymbol)),
7
+ devDependencies: Schema.optional(Schema.Array(ReportSymbol)),
8
+ exports: Schema.optional(Schema.Array(ReportSymbol)),
9
+ file: Schema.String,
10
+ files: Schema.optional(Schema.Array(ReportSymbol)),
11
+ nsExports: Schema.optional(Schema.Array(ReportSymbol)),
12
+ nsTypes: Schema.optional(Schema.Array(ReportSymbol)),
13
+ optionalPeerDependencies: Schema.optional(Schema.Array(ReportSymbol)),
14
+ types: Schema.optional(Schema.Array(ReportSymbol)),
15
+ unlisted: Schema.optional(Schema.Array(ReportSymbol)),
16
+ });
17
+ const Report = Schema.Struct({ issues: Schema.Array(Issue) });
18
+
19
+ const REPAIRS = [
20
+ ["dependencies", "Unused dependency. Remove it from the package manifest if it is no longer needed"],
21
+ ["devDependencies", "Unused development dependency. Remove it from the package manifest if it is no longer needed"],
22
+ ["exports", "Unused export. Remove the export or use it from an entry point"],
23
+ ["files", "Unused file. Remove it or reach it from a declared entry point"],
24
+ ["nsExports", "Unused namespace export. Remove the export or use it from an entry point"],
25
+ ["nsTypes", "Unused namespace type. Remove the export or use it from an entry point"],
26
+ ["optionalPeerDependencies", "Unused optional peer dependency. Remove it from the package manifest if it is no longer needed"],
27
+ ["types", "Unused exported type. Remove the export or use it from an entry point"],
28
+ ["unlisted", "Missing package dependency. Declare it in the importing package's manifest"],
29
+ ] as const;
30
+
31
+ export const KNIP_ISSUES = REPAIRS.map(([kind]) => kind);
32
+
33
+ export function knipFindings(stdout: string): readonly Finding[] {
34
+ const report = Schema.decodeUnknownSync(Schema.fromJsonString(Report))(stdout);
35
+ return report.issues.flatMap((issue) =>
36
+ REPAIRS.flatMap(([kind, repair]) => {
37
+ const symbols = issue[kind];
38
+ return (symbols ?? []).map((symbol) => ({
39
+ file: issue.file,
40
+ line: symbol.line,
41
+ message: `${repair}: ${symbol.name}.`,
42
+ subject: `${kind}:${symbol.name}`,
43
+ }));
44
+ }),
45
+ );
46
+ }
@@ -0,0 +1,60 @@
1
+ import { createRequire } from "node:module";
2
+ import { basename, dirname, join, posix } from "node:path";
3
+ import process from "node:process";
4
+ import { NodeServices } from "@effect/platform-node";
5
+ import { Effect, FileSystem, Stream } from "effect";
6
+ import { ChildProcess, ChildProcessSpawner } from "effect/process";
7
+ import type { RuleInputs } from "#rule.ts";
8
+ import { knipConfiguration } from "./configuration.ts";
9
+ import { entryPointFindings } from "./entryPointFindings.ts";
10
+ import { KNIP_ISSUES, knipFindings } from "./findings.ts";
11
+ import { sourceConfig } from "./sourceConfig.ts";
12
+
13
+ const BIN = join(dirname(createRequire(import.meta.url).resolve("knip")), "..", "bin", "knip.js");
14
+ export async function runKnip(inputs: RuleInputs) {
15
+ if ((await inputs.readText("package.json")) === undefined) {
16
+ return [];
17
+ }
18
+ const configuration = await knipConfiguration(inputs);
19
+ const checked = new Set([...inputs.files, ...Object.keys(configuration.workspaces).map((directory) => posix.join(directory, "package.json"))]);
20
+ const findings = await Effect.runPromise(
21
+ Effect.scoped(
22
+ Effect.gen(function* () {
23
+ const fs = yield* FileSystem.FileSystem;
24
+ const temporary = yield* fs.makeTempDirectoryScoped({ prefix: "quality-knip-" });
25
+ const config = join(temporary, "knip.json");
26
+ yield* fs.writeFileString(config, JSON.stringify(configuration));
27
+ const tsconfig = yield* sourceConfig(inputs, Object.keys(configuration.workspaces), basename(temporary));
28
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
29
+ const child = yield* spawner.spawn(
30
+ ChildProcess.make(
31
+ process.execPath,
32
+ [
33
+ "--conditions=source",
34
+ BIN,
35
+ "--config",
36
+ config,
37
+ "--tsConfig",
38
+ tsconfig,
39
+ "--reporter",
40
+ "json",
41
+ "--include",
42
+ KNIP_ISSUES.join(","),
43
+ "--no-progress",
44
+ ],
45
+ { cwd: inputs.root, env: { "JITI_TRY_NATIVE": "true" }, extendEnv: true, stdin: "ignore" },
46
+ ),
47
+ );
48
+ const [stdout, stderr, code] = yield* Effect.all(
49
+ [Stream.mkString(Stream.decodeText(child.stdout)), Stream.mkString(Stream.decodeText(child.stderr)), child.exitCode],
50
+ { concurrency: "unbounded" },
51
+ );
52
+ if (Number(code) > 1) {
53
+ return yield* Effect.fail(new Error(`knip failed: ${stderr || `exit code ${code}`}`));
54
+ }
55
+ return knipFindings(stdout).filter((finding) => checked.has(finding.file));
56
+ }),
57
+ ).pipe(Effect.provide(NodeServices.layer)),
58
+ );
59
+ return entryPointFindings(inputs, findings);
60
+ }
@@ -0,0 +1,20 @@
1
+ import { join, posix, resolve } from "node:path";
2
+ import { Effect, FileSystem } from "effect";
3
+ import type { RuleInputs } from "#rule.ts";
4
+
5
+ export const sourceConfig = Effect.fn("Knip.sourceConfig")(function* (inputs: RuleInputs, directories: readonly string[], id: string) {
6
+ const fs = yield* FileSystem.FileSystem;
7
+ const relative = posix.join("node_modules", ".cache", "quality", id, "tsconfig.json");
8
+ for (const directory of directories) {
9
+ const folder = join(inputs.root, directory, "node_modules", ".cache", "quality", id);
10
+ yield* fs.makeDirectory(folder, { recursive: true });
11
+ yield* Effect.addFinalizer(() => fs.remove(folder, { recursive: true }).pipe(Effect.orDie));
12
+ const parents = yield* Effect.forEach(["tsconfig.json", "tsconfig.build.json"], (file) =>
13
+ Effect.promise(() => inputs.readText(posix.join(directory, file))).pipe(
14
+ Effect.map((text) => (text === undefined ? [] : [resolve(inputs.root, directory, file)])),
15
+ ),
16
+ );
17
+ yield* fs.writeFileString(join(folder, "tsconfig.json"), JSON.stringify({ extends: parents.flat(), files: [] }));
18
+ }
19
+ return relative;
20
+ });
@@ -4,7 +4,7 @@ import { nativeEffectCall } from "./nativeEffectCall.ts";
4
4
  import type { Diagnostic } from "./report.ts";
5
5
  import { nodeAt, offsetOf, type Syntax, syntaxOf } from "./syntax.ts";
6
6
 
7
- const RECOGNIZED: ReadonlySet<string> = new Set(["lint/nursery/noComponentHookFactories", "lint/style/noDoneCallback"]);
7
+ const RECOGNIZED: ReadonlySet<string> = new Set(["lint/correctness/noComponentHookFactories", "lint/style/noDoneCallback"]);
8
8
 
9
9
  function generatorParameter(node: ts.Node): boolean {
10
10
  const parameter = node.parent;
@@ -45,7 +45,7 @@ function misclassified(diagnostic: Diagnostic, syntax: Syntax): boolean {
45
45
  switch (diagnostic.category) {
46
46
  case "lint/style/noDoneCallback":
47
47
  return generatorParameter(node);
48
- case "lint/nursery/noComponentHookFactories":
48
+ case "lint/correctness/noComponentHookFactories":
49
49
  return tagHandler(node, syntax);
50
50
  default:
51
51
  return false;
@@ -0,0 +1,104 @@
1
+ import ts from "typescript";
2
+ import { packageNameOf } from "#imports/packageName.ts";
3
+ import { codeSpans, type MarkdownLine, markdownLines } from "./markdownLines.ts";
4
+
5
+ export interface DocumentedImport {
6
+ readonly line: number;
7
+ readonly name?: string;
8
+ readonly specifier: string;
9
+ readonly typeOnly?: boolean;
10
+ }
11
+
12
+ export interface DocumentedScope {
13
+ readonly owner?: string | undefined;
14
+ readonly packages: (name: string) => boolean;
15
+ }
16
+
17
+ const CODE_LANGUAGES: ReadonlySet<string> = new Set(["js", "jsx", "mjs", "mts", "ts", "tsx", "typescript"]);
18
+
19
+ const MODULE = /^(?:@[\w.-]+\/)?[\w.-]+\/[\w./-]+\.[cm]?[jt]sx?$/u;
20
+
21
+ const OWN_MODULE = /^[\w-]+(?:\/[\w.-]+)*\.ts$/u;
22
+
23
+ const NAMED = /`(?<name>\w+)` from `(?<specifier>[^`]+)`/gu;
24
+
25
+ const HEADING = /^(?<level>#{1,6})\s+(?<title>.+)$/u;
26
+
27
+ function declarationImports(statement: ts.Statement, line: number): readonly DocumentedImport[] {
28
+ if (!(ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier))) {
29
+ return [];
30
+ }
31
+ const specifier = statement.moduleSpecifier.text;
32
+ const clause = statement.importClause;
33
+ const named = clause?.namedBindings !== undefined && ts.isNamedImports(clause.namedBindings) ? clause.namedBindings.elements : [];
34
+ return [
35
+ { line, specifier },
36
+ ...(clause?.name === undefined ? [] : [{ line, name: "default", specifier, typeOnly: clause.isTypeOnly }]),
37
+ ...named.map((entry) => ({
38
+ line,
39
+ name: (entry.propertyName ?? entry.name).text,
40
+ specifier,
41
+ typeOnly: clause?.isTypeOnly === true || entry.isTypeOnly,
42
+ })),
43
+ ];
44
+ }
45
+
46
+ function codeBlocks(lines: readonly MarkdownLine[]): ReadonlyArray<{ readonly first: number; readonly text: string }> {
47
+ const blocks: Array<{ first: number; text: string[] }> = [];
48
+ for (const [index, line] of lines.entries()) {
49
+ if (line.kind === "code" && CODE_LANGUAGES.has(line.language)) {
50
+ const last = blocks.at(-1);
51
+ if (last !== undefined && lines[index - 1]?.kind === "code") {
52
+ last.text.push(line.text);
53
+ } else {
54
+ blocks.push({ first: line.number, text: [line.text] });
55
+ }
56
+ }
57
+ }
58
+ return blocks.map((block) => ({ first: block.first, text: block.text.join("\n") }));
59
+ }
60
+
61
+ function codeImports(lines: readonly MarkdownLine[]): readonly DocumentedImport[] {
62
+ return codeBlocks(lines).flatMap((block) => {
63
+ const file = ts.createSourceFile("block.tsx", block.text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
64
+ return file.statements.flatMap((statement) =>
65
+ declarationImports(statement, block.first + file.getLineAndCharacterOfPosition(statement.getStart(file)).line),
66
+ );
67
+ });
68
+ }
69
+
70
+ function apiLevel(text: string, current: number | undefined): number | undefined {
71
+ const heading = HEADING.exec(text);
72
+ if (heading === null) {
73
+ return current;
74
+ }
75
+ const level = heading.groups?.level?.length ?? 0;
76
+ if (/^API\b/u.test(heading.groups?.title ?? "")) {
77
+ return level;
78
+ }
79
+ return current !== undefined && level <= current ? undefined : current;
80
+ }
81
+
82
+ function firstCell(text: string): string {
83
+ return text.startsWith("|") ? (text.split("|")[1] ?? "") : "";
84
+ }
85
+
86
+ function proseImports(lines: readonly MarkdownLine[], owner: string | undefined): readonly DocumentedImport[] {
87
+ const found: DocumentedImport[] = [];
88
+ let api: number | undefined;
89
+ for (const { number: line, text } of lines.filter((entry) => entry.kind === "prose")) {
90
+ api = apiLevel(text, api);
91
+ found.push(...codeSpans(text).flatMap((span) => (MODULE.test(span) ? [{ line, specifier: span }] : [])));
92
+ found.push(...[...text.matchAll(NAMED)].map((match) => ({ line, name: match.groups?.name ?? "", specifier: match.groups?.specifier ?? "" })));
93
+ if (owner !== undefined) {
94
+ const listed = api === undefined ? firstCell(text) : text;
95
+ found.push(...codeSpans(listed).flatMap((span) => (OWN_MODULE.test(span) ? [{ line, specifier: `${owner}/${span}` }] : [])));
96
+ }
97
+ }
98
+ return found;
99
+ }
100
+
101
+ export function documentedImports(markdown: string, scope: DocumentedScope): readonly DocumentedImport[] {
102
+ const lines = markdownLines(markdown);
103
+ return [...codeImports(lines), ...proseImports(lines, scope.owner)].filter((entry) => scope.packages(packageNameOf(entry.specifier)));
104
+ }
@@ -0,0 +1,44 @@
1
+ import { join, posix } from "node:path";
2
+ import ts from "typescript";
3
+ import { exportEntry, exportTargets } from "#imports/packageExports.ts";
4
+ import type { WorkspacePackage } from "#imports/workspace.ts";
5
+
6
+ export type DocumentedModule = { readonly kind: "missing" } | { readonly kind: "private" } | { readonly kind: "source"; readonly path: string };
7
+
8
+ const BUILT = /^\.\/dist\/(?<path>.+?)(?:\.d)?\.[cm]?[jt]s$/u;
9
+
10
+ const SOURCE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts"];
11
+
12
+ const MISSING: DocumentedModule = { kind: "missing" };
13
+
14
+ function sourcesFor(target: string): readonly string[] {
15
+ const built = BUILT.exec(target)?.groups?.path;
16
+ return built === undefined ? [target] : [target, ...SOURCE_EXTENSIONS.map((extension) => `./src/${built}${extension}`)];
17
+ }
18
+
19
+ function found(root: string, directory: string, candidates: readonly string[]): DocumentedModule {
20
+ const path = candidates.map((candidate) => posix.join(directory, candidate)).find((candidate) => ts.sys.fileExists(join(root, candidate)));
21
+ return path === undefined ? MISSING : { kind: "source", path };
22
+ }
23
+
24
+ export function documentedModule(root: string, owner: WorkspacePackage, exports: unknown, specifier: string): DocumentedModule {
25
+ const rest = specifier.slice(owner.name.length);
26
+ const subpath = rest === "" ? "." : `.${rest}`;
27
+ if (exports === undefined || exports === null) {
28
+ return found(root, owner.directory, [subpath]);
29
+ }
30
+ const entry = exportEntry(typeof exports === "string" || Array.isArray(exports) ? { ".": exports } : exports, subpath);
31
+ if (entry === undefined) {
32
+ return MISSING;
33
+ }
34
+ if (entry[1] === null) {
35
+ return { kind: "private" };
36
+ }
37
+ const [prefix = "", suffix = ""] = entry[0].split("*");
38
+ const star = subpath.slice(prefix.length, subpath.length - suffix.length);
39
+ return found(
40
+ root,
41
+ owner.directory,
42
+ exportTargets(entry[1]).flatMap((target) => sourcesFor(target.replace("*", star))),
43
+ );
44
+ }
@@ -0,0 +1,27 @@
1
+ import ts from "typescript";
2
+ import { ownExports } from "#naming/ownExports.ts";
3
+ import { parse } from "#rules/parse.ts";
4
+
5
+ function isDefault(statement: ts.Statement): boolean {
6
+ if (ts.isExportAssignment(statement)) {
7
+ return !statement.isExportEquals;
8
+ }
9
+ const modifiers = ts.canHaveModifiers(statement) ? (ts.getModifiers(statement) ?? []) : [];
10
+ return modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword);
11
+ }
12
+
13
+ function reexports(statement: ts.Statement): boolean {
14
+ return ts.isExportDeclaration(statement) && statement.moduleSpecifier !== undefined;
15
+ }
16
+
17
+ // A module that re-exports another may export any name that module does, so only a module without re-exports gets a definite answer.
18
+ export function exportsName(path: string, text: string, name: string): boolean | undefined {
19
+ const source = parse({ lines: [], path, text });
20
+ if (source === undefined || source.statements.some(reexports)) {
21
+ return undefined;
22
+ }
23
+ if (name === "default") {
24
+ return source.statements.some(isDefault);
25
+ }
26
+ return ownExports(source).some((entry) => entry.name === name);
27
+ }
@@ -0,0 +1,52 @@
1
+ import type { MarkdownLine } from "./markdownLines.ts";
2
+
3
+ const ATX = /^ {0,3}#{1,6}\s+(?<title>.*?)(?:\s+#+)?\s*$/u;
4
+
5
+ const SETEXT = /^ {0,3}(?:=+|-+)\s*$/u;
6
+
7
+ const HTML_ANCHOR = /<a\s[^>]*\b(?:id|name)="(?<anchor>[^"]+)"/gu;
8
+
9
+ const LINK = /!?\[(?<text>[^\]]*)\]\([^)]*\)/gu;
10
+
11
+ const TAG = /<[^>]+>/gu;
12
+
13
+ const NOT_SLUG = /[^\p{L}\p{M}\p{N}\p{Pc} -]/gu;
14
+
15
+ export function headingSlug(title: string): string {
16
+ return title.replace(LINK, "$<text>").replace(TAG, "").replaceAll("`", "").trim().toLowerCase().replace(NOT_SLUG, "").replaceAll(" ", "-");
17
+ }
18
+
19
+ function titleAt(lines: readonly MarkdownLine[], index: number): string | undefined {
20
+ const line = lines[index];
21
+ if (line?.kind !== "prose") {
22
+ return undefined;
23
+ }
24
+ const atx = ATX.exec(line.text)?.groups?.title;
25
+ if (atx !== undefined) {
26
+ return atx;
27
+ }
28
+ const next = lines[index + 1];
29
+ const underlined = next?.kind === "prose" && SETEXT.test(next.text) && line.text.trim() !== "" && !SETEXT.test(line.text);
30
+ return underlined ? line.text.trim() : undefined;
31
+ }
32
+
33
+ // GitHub numbers a repeated heading's anchor -1, -2 and so on, in document order.
34
+ export function headingAnchors(lines: readonly MarkdownLine[]): ReadonlySet<string> {
35
+ const anchors = new Set<string>();
36
+ const seen = new Map<string, number>();
37
+ for (const [index, line] of lines.entries()) {
38
+ const title = titleAt(lines, index);
39
+ if (title !== undefined) {
40
+ const slug = headingSlug(title);
41
+ const count = seen.get(slug) ?? 0;
42
+ seen.set(slug, count + 1);
43
+ anchors.add(count === 0 ? slug : `${slug}-${count}`);
44
+ }
45
+ if (line.kind === "prose") {
46
+ for (const match of line.text.matchAll(HTML_ANCHOR)) {
47
+ anchors.add((match.groups?.anchor ?? "").toLowerCase());
48
+ }
49
+ }
50
+ }
51
+ return anchors;
52
+ }
@@ -0,0 +1,62 @@
1
+ import { Effect } from "effect";
2
+ import { packageNameOf } from "#imports/packageName.ts";
3
+ import type { WorkspacePackage } from "#imports/workspace.ts";
4
+ import type { Finding } from "#rule.ts";
5
+ import { type DocumentedImport, documentedImports } from "./documentedImports.ts";
6
+ import { type DocumentedModule, documentedModule } from "./documentedModule.ts";
7
+ import { exportsName } from "./exportsName.ts";
8
+
9
+ export interface ImportContext {
10
+ readonly exports: ReadonlyMap<string, unknown>;
11
+ readonly owner: string | undefined;
12
+ readonly packages: ReadonlyMap<string, WorkspacePackage>;
13
+ readonly readText: (path: string) => Effect.Effect<string | undefined>;
14
+ readonly root: string;
15
+ }
16
+
17
+ function missingExport(specifier: string, path: string, name: string): string {
18
+ return name === "default"
19
+ ? `"${specifier}" has no default export. Import a named export of ${path}, or the module whose default export you mean.`
20
+ : `"${specifier}" does not export ${name}. Name an export of ${path}, or the module that exports ${name}.`;
21
+ }
22
+
23
+ function problem(
24
+ context: ImportContext,
25
+ entry: DocumentedImport,
26
+ module: DocumentedModule,
27
+ owner: WorkspacePackage,
28
+ ): Effect.Effect<string | undefined> {
29
+ if (module.kind === "missing") {
30
+ return Effect.succeed(`"${entry.specifier}" names no module of ${owner.name}. Use the path of a module its package.json "exports" maps.`);
31
+ }
32
+ if (module.kind === "private") {
33
+ return Effect.succeed(
34
+ `"${entry.specifier}" is private: the package.json "exports" of ${owner.name} blocks it. Document a module the package exports.`,
35
+ );
36
+ }
37
+ const name = entry.name;
38
+ if (name === undefined) {
39
+ return Effect.succeed(undefined);
40
+ }
41
+ return Effect.map(context.readText(module.path), (text) =>
42
+ text !== undefined && exportsName(module.path, text, name) === false ? missingExport(entry.specifier, module.path, name) : undefined,
43
+ );
44
+ }
45
+
46
+ export function importFindings(context: ImportContext, file: string, markdown: string): Effect.Effect<readonly Finding[]> {
47
+ const entries = documentedImports(markdown, { owner: context.owner, packages: (name) => context.packages.has(name) });
48
+ const unique = [...new Map(entries.map((entry) => [`${entry.line} ${entry.specifier} ${entry.name ?? ""}`, entry])).values()];
49
+ return Effect.map(
50
+ Effect.forEach(unique, (entry) => {
51
+ const owner = context.packages.get(packageNameOf(entry.specifier));
52
+ if (owner === undefined) {
53
+ return Effect.succeed([]);
54
+ }
55
+ const module = documentedModule(context.root, owner, context.exports.get(owner.name), entry.specifier);
56
+ return Effect.map(problem(context, entry, module, owner), (message): readonly Finding[] =>
57
+ message === undefined ? [] : [{ file, line: entry.line, message, subject: entry.specifier }],
58
+ );
59
+ }),
60
+ (findings) => [...new Map(findings.flat().map((finding) => [`${finding.line} ${finding.message}`, finding])).values()],
61
+ );
62
+ }
@@ -0,0 +1,6 @@
1
+ import { posix } from "node:path";
2
+
3
+ // Released changelogs keep the links and commands of their release, so a later change does not rewrite history.
4
+ export function isDocument(path: string): boolean {
5
+ return path.endsWith(".md") && posix.basename(path) !== "CHANGELOG.md";
6
+ }
@@ -0,0 +1,90 @@
1
+ import { join, posix } from "node:path";
2
+ import { Effect, Result } from "effect";
3
+ import ts from "typescript";
4
+ import type { Finding } from "#rule.ts";
5
+ import type { MarkdownLine } from "./markdownLines.ts";
6
+ import { markdownLinks } from "./markdownLinks.ts";
7
+ import { type Repository, repositoryLink } from "./repositoryLink.ts";
8
+
9
+ export interface LinkContext {
10
+ readonly anchors: (path: string) => Effect.Effect<ReadonlySet<string> | undefined>;
11
+ readonly published: string | undefined;
12
+ readonly repository: Repository | undefined;
13
+ readonly root: string;
14
+ }
15
+
16
+ interface Destination {
17
+ readonly anchor: string | undefined;
18
+ readonly path: string;
19
+ }
20
+
21
+ const SCHEME = /^(?:[a-z][\d+.a-z-]*:|\/\/)/iu;
22
+
23
+ function decoded(text: string): string {
24
+ return Result.getOrElse(
25
+ Result.try(() => decodeURIComponent(text)),
26
+ () => text,
27
+ );
28
+ }
29
+
30
+ function destination(file: string, target: string, repository: Repository | undefined): Destination | undefined {
31
+ if (SCHEME.test(target)) {
32
+ const linked = repositoryLink(target, repository);
33
+ return linked === undefined ? undefined : { anchor: linked.anchor, path: posix.normalize(decoded(linked.path) || ".") };
34
+ }
35
+ const hash = target.indexOf("#");
36
+ const path = decoded(hash === -1 ? target : target.slice(0, hash));
37
+ const anchor = hash === -1 ? undefined : target.slice(hash + 1);
38
+ if (path === "") {
39
+ return { anchor, path: file };
40
+ }
41
+ return { anchor, path: path.startsWith("/") ? posix.normalize(path.slice(1) || ".") : posix.join(posix.dirname(file), path) };
42
+ }
43
+
44
+ function inside(path: string, directory: string): boolean {
45
+ return path === directory || path.startsWith(`${directory}/`);
46
+ }
47
+
48
+ function exampleUrl(repository: Repository | undefined, to: Destination): string {
49
+ const anchor = to.anchor === undefined ? "" : `#${to.anchor}`;
50
+ return repository === undefined ? "" : `, such as https://github.com/${repository.owner}/${repository.name}/blob/HEAD/${to.path}${anchor}`;
51
+ }
52
+
53
+ function placement(context: LinkContext, target: string, to: Destination): string | undefined {
54
+ if (to.path === ".." || to.path.startsWith("../")) {
55
+ return `"${target}" leaves the repository. Link to a file inside it, or use an absolute URL.`;
56
+ }
57
+ const absolute = join(context.root, to.path);
58
+ if (!(ts.sys.fileExists(absolute) || ts.sys.directoryExists(absolute))) {
59
+ return `"${target}" links to ${to.path}, which does not exist. Link to the file's current path, or remove the link.`;
60
+ }
61
+ if (context.published !== undefined && !SCHEME.test(target) && !inside(to.path, context.published)) {
62
+ return `"${target}" leaves its package, and npm shows ${context.published}/README.md without the repository around it. Use an absolute URL${exampleUrl(context.repository, to)}.`;
63
+ }
64
+ return undefined;
65
+ }
66
+
67
+ function problem(context: LinkContext, target: string, to: Destination): Effect.Effect<string | undefined> {
68
+ const misplaced = placement(context, target, to);
69
+ const anchor = to.anchor;
70
+ if (misplaced !== undefined || anchor === undefined || anchor === "" || !to.path.endsWith(".md")) {
71
+ return Effect.succeed(misplaced);
72
+ }
73
+ return Effect.map(context.anchors(to.path), (anchors) =>
74
+ anchors === undefined || anchors.has(decoded(anchor).toLowerCase())
75
+ ? undefined
76
+ : `"${target}" links to the heading #${anchor}, which ${to.path} does not have. Link to a current heading; GitHub forms its anchor from the heading text.`,
77
+ );
78
+ }
79
+
80
+ export function linkFindings(context: LinkContext, file: string, lines: readonly MarkdownLine[]): Effect.Effect<readonly Finding[]> {
81
+ return Effect.map(
82
+ Effect.forEach(markdownLinks(lines), (link) => {
83
+ const to = destination(file, link.target, context.repository);
84
+ return Effect.map(to === undefined ? Effect.succeed(undefined) : problem(context, link.target, to), (message): readonly Finding[] =>
85
+ message === undefined ? [] : [{ file, line: link.line, message, subject: link.target }],
86
+ );
87
+ }),
88
+ (findings) => findings.flat(),
89
+ );
90
+ }
@@ -0,0 +1,56 @@
1
+ import { linesOf } from "#inventory/linesOf.ts";
2
+
3
+ export type MarkdownLineKind = "code" | "fence" | "prose";
4
+
5
+ export interface MarkdownLine {
6
+ readonly kind: MarkdownLineKind;
7
+ readonly language: string;
8
+ readonly number: number;
9
+ readonly text: string;
10
+ }
11
+
12
+ interface OpenFence {
13
+ readonly language: string;
14
+ readonly marker: string;
15
+ }
16
+
17
+ const FENCE = /^ {0,3}(?<marker>`{3,}|~{3,})\s*(?<info>[^`\s]*)[^`]*$/u;
18
+
19
+ function opening(text: string): OpenFence | undefined {
20
+ const match = FENCE.exec(text);
21
+ const marker = match?.groups?.marker;
22
+ return marker === undefined ? undefined : { language: (match?.groups?.info ?? "").toLowerCase(), marker };
23
+ }
24
+
25
+ function closes(text: string, open: OpenFence): boolean {
26
+ const trimmed = text.trim();
27
+ return trimmed.startsWith(open.marker) && /^(?:`+|~+)$/u.test(trimmed);
28
+ }
29
+
30
+ export function markdownLines(markdown: string): readonly MarkdownLine[] {
31
+ const lines: MarkdownLine[] = [];
32
+ let open: OpenFence | undefined;
33
+ for (const [index, text] of linesOf(markdown).entries()) {
34
+ const number = index + 1;
35
+ if (open === undefined) {
36
+ open = opening(text);
37
+ lines.push({ kind: open === undefined ? "prose" : "fence", language: "", number, text });
38
+ } else if (closes(text, open)) {
39
+ lines.push({ kind: "fence", language: open.language, number, text });
40
+ open = undefined;
41
+ } else {
42
+ lines.push({ kind: "code", language: open.language, number, text });
43
+ }
44
+ }
45
+ return lines;
46
+ }
47
+
48
+ const CODE_SPAN = /(?<ticks>`+)(?<code>.+?)\k<ticks>/gu;
49
+
50
+ export function codeSpans(text: string): readonly string[] {
51
+ return [...text.matchAll(CODE_SPAN)].map((match) => (match.groups?.code ?? "").trim());
52
+ }
53
+
54
+ export function withoutCodeSpans(text: string): string {
55
+ return text.replace(CODE_SPAN, "");
56
+ }
@@ -0,0 +1,33 @@
1
+ import { type MarkdownLine, withoutCodeSpans } from "./markdownLines.ts";
2
+
3
+ export interface MarkdownLink {
4
+ readonly line: number;
5
+ readonly target: string;
6
+ }
7
+
8
+ const INLINE = /\]\(\s*(?<target><[^>]*>|[^\s)]+)/gu;
9
+
10
+ const DEFINITION = /^ {0,3}\[[^\]]+\]:\s*(?<target><[^>]*>|\S+)/u;
11
+
12
+ const ATTRIBUTE = /\b(?:href|src)="(?<target>[^"]+)"/gu;
13
+
14
+ function unwrapped(target: string): string {
15
+ return target.startsWith("<") && target.endsWith(">") ? target.slice(1, -1) : target;
16
+ }
17
+
18
+ function targetsIn(text: string): readonly string[] {
19
+ const prose = withoutCodeSpans(text);
20
+ const definition = DEFINITION.exec(prose)?.groups?.target;
21
+ return [
22
+ ...[...prose.matchAll(INLINE)].map((match) => match.groups?.target ?? ""),
23
+ ...(definition === undefined ? [] : [definition]),
24
+ ...[...prose.matchAll(ATTRIBUTE)].map((match) => match.groups?.target ?? ""),
25
+ ].map(unwrapped);
26
+ }
27
+
28
+ export function markdownLinks(lines: readonly MarkdownLine[]): readonly MarkdownLink[] {
29
+ return lines
30
+ .filter((line) => line.kind === "prose")
31
+ .flatMap((line) => targetsIn(line.text).map((target) => ({ line: line.number, target })))
32
+ .filter((link) => link.target !== "");
33
+ }