@sshkeda/check 1.0.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +19 -6
  2. package/docs/how-to-make-check-pass.md +4 -14
  3. package/package.json +4 -4
  4. package/src/internal/ban-abbreviated-words-in-declared-names.ts +0 -4
  5. package/src/internal/ban-checked-members-outside-calls.ts +8 -8
  6. package/src/internal/ban-comments.ts +0 -1
  7. package/src/internal/ban-comparing-or-switching-on-tag.ts +50 -10
  8. package/src/internal/ban-deadlines-inside-tests.ts +3 -4
  9. package/src/internal/ban-declared-values.ts +2 -5
  10. package/src/internal/ban-dropped-failures-detached-fibers-sleeps-and-untraced-functions.ts +0 -2
  11. package/src/internal/ban-failures-collected-as-results.ts +0 -4
  12. package/src/internal/ban-fallbacks-of-named-recoveries.ts +1 -29
  13. package/src/internal/ban-function-overloads.ts +0 -4
  14. package/src/internal/ban-global-error-in-failure-types.ts +10 -15
  15. package/src/internal/ban-instanceof-in-effect-recovery-callbacks.ts +17 -26
  16. package/src/internal/ban-let-and-effect-mutable-ref.ts +0 -8
  17. package/src/internal/ban-logic-in-index-files.ts +0 -3
  18. package/src/internal/ban-namespaces-used-without-a-member.ts +0 -3
  19. package/src/internal/ban-node-builtins-that-effect-replaces.ts +0 -3
  20. package/src/internal/ban-parsing-outside-data-without-a-schema.ts +0 -4
  21. package/src/internal/ban-re-exports.ts +54 -18
  22. package/src/internal/ban-reading-the-clock-and-sleeping-outside-effect.ts +88 -4
  23. package/src/internal/ban-recovering-file-system-exists.ts +300 -0
  24. package/src/internal/ban-retired-words-in-names.ts +1 -4
  25. package/src/internal/ban-retries-without-a-wait.ts +292 -0
  26. package/src/internal/ban-scanning-directories-with-bun-glob.ts +0 -3
  27. package/src/internal/ban-shebang-lines.ts +0 -4
  28. package/src/internal/ban-timer-globals-and-the-global-object.ts +0 -1
  29. package/src/internal/ban-timer-schedules-without-deadlines.ts +129 -45
  30. package/src/internal/ban-type-and-interface-declarations.ts +0 -4
  31. package/src/internal/ban-type-predicates.ts +0 -4
  32. package/src/internal/ban-unknown-in-function-signatures.ts +49 -13
  33. package/src/internal/ban-vague-error-class-names.ts +0 -4
  34. package/src/internal/ban-vague-file-names.ts +3 -7
  35. package/src/internal/ban-what-a-file-is-not-granted.ts +37 -14
  36. package/src/internal/ban-while-do-while-and-for-loops.ts +0 -4
  37. package/src/internal/ban-writing-captured-objects-inside-effect-callbacks.ts +210 -0
  38. package/src/internal/confine-service-declarations-to-granted-files.ts +0 -7
  39. package/src/internal/confine-the-stdio-service-to-terminal-output.ts +2 -16
  40. package/src/internal/define-the-lint-plugin-and-configs.ts +6 -0
  41. package/src/internal/keep-assertions-in-the-test-home-and-ban-test-runners.ts +0 -6
  42. package/src/internal/keep-effect-testing-helpers-in-test-files.ts +2 -14
  43. package/src/internal/require-a-named-const-for-compound-conditions.ts +0 -4
  44. package/src/internal/require-capital-snake-case-and-as-const-on-literal-constants.ts +0 -4
  45. package/src/internal/require-service-keys-to-end-with-their-class-name.ts +5 -2
  46. package/src/internal/resolve-what-an-expression-imports.ts +115 -28
  47. package/src/internal/visit-every-declared-name.ts +13 -0
  48. package/src/lib/tasks/internal/declare-the-check-task.ts +2 -0
  49. package/src/lib/tasks/internal/declare-the-checker-queries-task.ts +2 -1
  50. package/src/lib/tasks/lib/check-effect-diagnostics-with-effect-tsgo/index.ts +2 -1
  51. package/src/lib/tasks/lib/check-effect-diagnostics-with-effect-tsgo/internal/check-effect-diagnostics-with-effect-tsgo.ts +17 -0
  52. package/src/lib/tasks/lib/check-import-boundaries/internal/decide-what-each-home-may-import.ts +62 -0
  53. package/src/lib/tasks/lib/check-import-boundaries/internal/find-import-boundary-violations.ts +215 -187
  54. package/src/lib/tasks/lib/confine-layer-provides-to-program-starts/internal/find-layer-provides-outside-program-starts.ts +13 -16
  55. package/src/lib/tasks/lib/confine-layer-provides-to-program-starts/internal/layer-provide-errors.ts +2 -1
  56. package/src/lib/tasks/lib/confine-layer-provides-to-program-starts/internal/resolve-imported-package-apis.ts +3 -1
  57. package/src/lib/tasks/lib/detect-duplicate-functions/index.ts +10 -0
  58. package/src/lib/tasks/lib/detect-duplicate-functions/internal/duplicate-function-errors.ts +23 -0
  59. package/src/lib/tasks/lib/detect-duplicate-functions/internal/find-duplicate-functions.ts +150 -0
  60. package/src/lib/tasks/lib/detect-duplicate-functions/internal/list-named-functions.ts +416 -0
  61. package/src/lib/tasks/lib/detect-inferrable-annotations/internal/find-inferrable-annotations.ts +31 -12
  62. package/src/lib/tasks/lib/enforce-file-layout/index.ts +6 -1
  63. package/src/lib/tasks/lib/enforce-file-layout/internal/file-layout-errors.ts +10 -0
  64. package/src/lib/tasks/lib/enforce-file-layout/internal/find-export-path-mismatches.ts +39 -7
  65. package/src/lib/tasks/lib/enforce-file-layout/internal/find-file-layout-violations.ts +8 -3
  66. package/src/lib/tasks/lib/enforce-file-types/index.ts +6 -1
  67. package/src/lib/tasks/lib/format-with-bun-fmt/internal/declare-the-formatting-task.ts +3 -2
  68. package/src/lib/tasks/lib/judge-index-re-exports/internal/find-index-re-export-violations.ts +27 -21
  69. package/src/lib/tasks/lib/lint-with-oxlint/index.ts +2 -1
  70. package/src/lib/tasks/lib/lint-with-oxlint/internal/check-lint-rules-with-oxlint.ts +11 -8
  71. package/src/lib/tasks/lib/lint-with-oxlint/internal/read-oxlint-json-report.ts +18 -2
  72. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/export-placement-errors.ts +12 -1
  73. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/find-export-placement-violations.ts +75 -21
  74. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/find-package-entry-sources.ts +146 -0
  75. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/find-the-importer-graph.ts +13 -188
  76. package/src/lib/tasks/lib/refuse-disable-directives/index.ts +2 -1
  77. package/src/lib/tasks/lib/refuse-disable-directives/internal/find-disable-directives.ts +9 -3
  78. package/src/lib/tasks/lib/refuse-error-mappings-that-end-streams/internal/find-error-mappings-to-done.ts +108 -9
  79. package/src/lib/tasks/lib/require-separate-service-layers/internal/find-service-layer-violations.ts +1 -5
  80. package/src/lib/tasks/lib/require-type-checking-every-linted-file/index.ts +2 -1
  81. package/src/lib/tasks/lib/require-type-checking-every-linted-file/internal/find-linted-files-not-type-checked.ts +2 -4
  82. package/src/lib/tasks/shared/check-each-nested-package.ts +13 -1
  83. package/src/lib/tasks/shared/classify-files-by-role.ts +5 -0
  84. package/src/lib/tasks/shared/count-the-line-of-an-offset.ts +20 -2
  85. package/src/lib/tasks/shared/create-the-module-resolver.ts +39 -23
  86. package/src/lib/tasks/shared/declare-lint-config-task.ts +2 -1
  87. package/src/lib/tasks/shared/declare-typescript-config-task.ts +30 -2
  88. package/src/lib/tasks/shared/find-unmet-typescript-config-requirements.ts +24 -7
  89. package/src/lib/tasks/shared/list-ignored-files-imported-by-source.ts +25 -16
  90. package/src/lib/tasks/shared/load-the-lint-config.ts +14 -12
  91. package/src/lib/tasks/shared/parse-config-files-that-import-from-check.ts +6 -7
  92. package/src/lib/tasks/shared/project-config-and-tool-errors.ts +63 -4
  93. package/src/lib/tasks/shared/provide-project-query-caches.ts +11 -0
  94. package/src/lib/tasks/shared/query-the-typescript-project.ts +108 -43
  95. package/src/lib/tasks/shared/resolve-absolute-paths.ts +4 -1
  96. package/src/lib/tasks/shared/resolve-module-requests.ts +131 -90
  97. package/src/lib/tasks/shared/run-tools-and-decode-their-reports.ts +15 -11
  98. package/src/shared/bans-each-permission-lifts.ts +4 -21
  99. package/src/shared/find-retired-words.ts +1 -1
  100. package/src/shared/lint-rule-messages-and-patterns.ts +7 -12
  101. package/src/shared/record-and-grant-permissions-by-path.ts +41 -65
@@ -0,0 +1,150 @@
1
+ import { Array as Arrays, Effect, FileSystem, Hash, Path, Predicate } from "effect";
2
+ import type { Node } from "oxc-parser";
3
+
4
+ import { inEachPackage } from "../../../shared/check-each-nested-package.ts";
5
+ import { isScript } from "../../../shared/classify-files-by-role.ts";
6
+ import { lineNumbersIn } from "../../../shared/count-the-line-of-an-offset.ts";
7
+ import { ownedFilesAmong } from "../../../shared/list-owned-files.ts";
8
+ import { existingPackageFiles } from "../../../shared/list-package-files.ts";
9
+ import { quietViolations } from "../../../shared/print-failures-and-keep-detail-in-the-trace.ts";
10
+ import { DuplicateFunction, DuplicateFunctions } from "./duplicate-function-errors.ts";
11
+ import { namedFunctionsIn } from "./list-named-functions.ts";
12
+
13
+ const DUPLICATE_FUNCTIONS = "duplicate-functions";
14
+ const CONCURRENT_FILE_READS = 32;
15
+ const FIELDS_OUTSIDE_THE_CODE: ReadonlySet<string> = new Set([
16
+ "start",
17
+ "end",
18
+ "range",
19
+ "loc",
20
+ "parent",
21
+ ]);
22
+
23
+ const codeOf = (values: readonly unknown[]): string =>
24
+ values
25
+ .map((value) => {
26
+ if (Arrays.isArray(value)) {
27
+ return `[${codeOf(value)}]`;
28
+ }
29
+ if (Predicate.isObject(value)) {
30
+ const fields = Object.entries(value).filter(
31
+ ([field]) => !FIELDS_OUTSIDE_THE_CODE.has(field),
32
+ );
33
+ const names = fields.map(([field]) => field).join(",");
34
+ return `{${names}:${codeOf(fields.map(([, fieldValue]) => fieldValue))}}`;
35
+ }
36
+ const text = String(value);
37
+ return `${typeof value}${text.length}:${text}`;
38
+ })
39
+ .join(",");
40
+
41
+ const hashOfTheCode = (values: readonly unknown[]): number =>
42
+ Hash.array(
43
+ values.map((value) => {
44
+ if (Arrays.isArray(value)) {
45
+ return hashOfTheCode(value);
46
+ }
47
+ if (Predicate.isObject(value)) {
48
+ return hashOfTheCode(
49
+ Object.entries(value)
50
+ .filter(([field]) => !FIELDS_OUTSIDE_THE_CODE.has(field))
51
+ .flat(),
52
+ );
53
+ }
54
+ return Hash.string(String(value));
55
+ }),
56
+ );
57
+
58
+ const isInside = (inner: { start: number; end: number }, outer: { start: number; end: number }) =>
59
+ inner !== outer && outer.start <= inner.start && inner.end <= outer.end;
60
+
61
+ export const duplicateFunctionViolations = (
62
+ sources: readonly { readonly path: string; readonly text: string }[],
63
+ shownPathOf = (path: string) => path,
64
+ ) => {
65
+ const candidatesIn = (
66
+ chosen: typeof sources,
67
+ isCandidate: (path: string, start: number) => boolean,
68
+ keyOf: (code: Node) => number | string,
69
+ ) =>
70
+ chosen.flatMap(({ path, text }) => {
71
+ const lineAt = lineNumbersIn(text);
72
+ return namedFunctionsIn(path, text)
73
+ .filter(({ start }) => isCandidate(path, start))
74
+ .map(({ name, start, end, code }) => ({
75
+ name,
76
+ path,
77
+ start,
78
+ end,
79
+ line: lineAt(start),
80
+ key: keyOf(code),
81
+ }));
82
+ });
83
+ const groupsOfCopies = (candidates: ReturnType<typeof candidatesIn>) =>
84
+ [...Map.groupBy(candidates, ({ key }) => key).values()].filter((group) => group.length > 1);
85
+ const likelyCopies = groupsOfCopies(
86
+ candidatesIn(
87
+ sources,
88
+ () => true,
89
+ (code) => hashOfTheCode([code]),
90
+ ),
91
+ ).flat();
92
+ const likelyCopyStarts = new Set(likelyCopies.map(({ path, start }) => `${path}:${start}`));
93
+ const likelyCopyPaths = new Set(likelyCopies.map(({ path }) => path));
94
+ const copyGroups = groupsOfCopies(
95
+ candidatesIn(
96
+ sources.filter(({ path }) => likelyCopyPaths.has(path)),
97
+ (path, start) => likelyCopyStarts.has(`${path}:${start}`),
98
+ (code) => codeOf([code]),
99
+ ),
100
+ );
101
+ const copiesByPath = Map.groupBy(copyGroups.flat(), ({ path }) => path);
102
+ const isInsideAnotherCopy = (member: (typeof copyGroups)[number][number]) =>
103
+ copiesByPath.get(member.path)?.some((outer) => isInside(member, outer)) === true;
104
+ return copyGroups
105
+ .filter((group) => !group.every((member) => isInsideAnotherCopy(member)))
106
+ .flatMap(([first, ...others]) =>
107
+ first === undefined
108
+ ? []
109
+ : [
110
+ new DuplicateFunction({
111
+ location: `${first.path}:${first.line}`,
112
+ functionName: first.name,
113
+ copies: others.map(({ path, line }) => `${shownPathOf(path)}:${line}`),
114
+ }),
115
+ ],
116
+ );
117
+ };
118
+
119
+ export const findDuplicateFunctions = (directory: string, shownDirectory = ".") =>
120
+ Effect.gen(function* () {
121
+ const fileSystem = yield* FileSystem.FileSystem;
122
+ const path = yield* Path.Path;
123
+ const scripts = (yield* ownedFilesAmong(
124
+ directory,
125
+ yield* existingPackageFiles(directory, []),
126
+ )).filter((file) => isScript(file));
127
+ const sources = yield* Effect.forEach(
128
+ scripts,
129
+ (file) =>
130
+ fileSystem
131
+ .readFileString(path.join(directory, file))
132
+ .pipe(Effect.map((text) => ({ path: file, text }))),
133
+ { concurrency: CONCURRENT_FILE_READS },
134
+ );
135
+ const violations = duplicateFunctionViolations(sources, (file) =>
136
+ path.join(shownDirectory, file),
137
+ );
138
+ if (violations.length > 0) {
139
+ return yield* new DuplicateFunctions({ violations });
140
+ }
141
+ });
142
+
143
+ export const duplicateFunctionsOfEachPackage = inEachPackage(
144
+ DUPLICATE_FUNCTIONS,
145
+ ".",
146
+ (packageDirectory) =>
147
+ findDuplicateFunctions(packageDirectory, packageDirectory).pipe(
148
+ quietViolations(DUPLICATE_FUNCTIONS),
149
+ ),
150
+ );
@@ -0,0 +1,416 @@
1
+ import { parseSync, Visitor } from "oxc-parser";
2
+ import type {
3
+ ArrowFunctionExpression,
4
+ BindingPattern,
5
+ BindingProperty,
6
+ BindingRestElement,
7
+ Class,
8
+ Directive,
9
+ Expression,
10
+ ForStatementInit,
11
+ Function as FunctionNode,
12
+ JSXElementName,
13
+ Node,
14
+ ParamPattern,
15
+ Statement,
16
+ } from "oxc-parser";
17
+
18
+ const IMPLICIT_ARGUMENTS = "arguments";
19
+ const OWN_THIS = "this";
20
+ const INTRINSIC_TAG = /^[a-z]|-/u;
21
+
22
+ const withoutParentheses = (expression: Expression): Expression =>
23
+ expression.type === "ParenthesizedExpression"
24
+ ? withoutParentheses(expression.expression)
25
+ : expression;
26
+
27
+ const isFunctionAssignedTo = (assigned: Expression | null) => {
28
+ const unwrapped = assigned === null ? undefined : withoutParentheses(assigned);
29
+ return unwrapped?.type === "ArrowFunctionExpression" || unwrapped?.type === "FunctionExpression";
30
+ };
31
+
32
+ const bindingNamesOf = (
33
+ pattern: BindingPattern | BindingProperty | BindingRestElement | ParamPattern | null,
34
+ ): readonly string[] => {
35
+ if (pattern === null) {
36
+ return [];
37
+ }
38
+ if (pattern.type === "Identifier") {
39
+ return [pattern.name];
40
+ }
41
+ if (pattern.type === "ObjectPattern") {
42
+ return pattern.properties.flatMap((property) => bindingNamesOf(property));
43
+ }
44
+ if (pattern.type === "ArrayPattern") {
45
+ return pattern.elements.flatMap((element) => bindingNamesOf(element));
46
+ }
47
+ if (pattern.type === "AssignmentPattern") {
48
+ return bindingNamesOf(pattern.left);
49
+ }
50
+ if (pattern.type === "RestElement") {
51
+ return bindingNamesOf(pattern.argument);
52
+ }
53
+ if (pattern.type === "Property") {
54
+ return bindingNamesOf(pattern.value);
55
+ }
56
+ return bindingNamesOf(pattern.parameter);
57
+ };
58
+
59
+ const lexicalNamesDeclaredBy = (statement: Directive | ForStatementInit | Statement | null) => {
60
+ const isLexicalDeclaration =
61
+ statement?.type === "VariableDeclaration" && statement.kind !== "var";
62
+ if (isLexicalDeclaration) {
63
+ return statement.declarations.flatMap((declarator) => bindingNamesOf(declarator.id));
64
+ }
65
+ if (statement?.type === "FunctionDeclaration") {
66
+ return statement.id === null ? [] : [statement.id.name];
67
+ }
68
+ if (statement?.type === "ClassDeclaration") {
69
+ return statement.id === null ? [] : [statement.id.name];
70
+ }
71
+ return statement?.type === "TSEnumDeclaration" ? [statement.id.name] : [];
72
+ };
73
+
74
+ const varNamesIn = (
75
+ statement: Directive | ForStatementInit | Statement | null,
76
+ ): readonly string[] => {
77
+ if (statement === null) {
78
+ return [];
79
+ }
80
+ if (statement.type === "VariableDeclaration") {
81
+ return statement.kind === "var"
82
+ ? statement.declarations.flatMap((declarator) => bindingNamesOf(declarator.id))
83
+ : [];
84
+ }
85
+ if (statement.type === "BlockStatement") {
86
+ return statement.body.flatMap((inner) => varNamesIn(inner));
87
+ }
88
+ if (statement.type === "IfStatement") {
89
+ return [...varNamesIn(statement.consequent), ...varNamesIn(statement.alternate)];
90
+ }
91
+ if (statement.type === "ForStatement") {
92
+ return [...varNamesIn(statement.init), ...varNamesIn(statement.body)];
93
+ }
94
+ const isForInOrOf = statement.type === "ForInStatement" || statement.type === "ForOfStatement";
95
+ if (isForInOrOf) {
96
+ const left = statement.left.type === "VariableDeclaration" ? varNamesIn(statement.left) : [];
97
+ return [...left, ...varNamesIn(statement.body)];
98
+ }
99
+ const isLoopOrLabel =
100
+ statement.type === "WhileStatement" ||
101
+ statement.type === "DoWhileStatement" ||
102
+ statement.type === "LabeledStatement";
103
+ if (isLoopOrLabel) {
104
+ return varNamesIn(statement.body);
105
+ }
106
+ if (statement.type === "TryStatement") {
107
+ return [
108
+ ...varNamesIn(statement.block),
109
+ ...(statement.handler === null ? [] : varNamesIn(statement.handler.body)),
110
+ ...varNamesIn(statement.finalizer),
111
+ ];
112
+ }
113
+ return statement.type === "SwitchStatement"
114
+ ? statement.cases.flatMap(({ consequent }) => consequent.flatMap((inner) => varNamesIn(inner)))
115
+ : [];
116
+ };
117
+
118
+ const componentRootOf = (name: JSXElementName): string | undefined => {
119
+ if (name.type === "JSXMemberExpression") {
120
+ return name.object.type === "JSXIdentifier" ? name.object.name : componentRootOf(name.object);
121
+ }
122
+ if (name.type === "JSXNamespacedName") {
123
+ return undefined;
124
+ }
125
+ return INTRINSIC_TAG.test(name.name) ? undefined : name.name;
126
+ };
127
+
128
+ export const namedFunctionsIn = (path: string, text: string) => {
129
+ const named: { name: string; start: number; end: number; code: Node }[] = [];
130
+ const scopes: { names: ReadonlySet<string>; isInAFunction: boolean }[] = [];
131
+ const open: { name: string; code: Node; depth: number; readsAnEnclosingLocal: boolean }[] = [];
132
+ const typePositions: Node[] = [];
133
+ const propertyNames = new Set<Node>();
134
+ const caseScopes = new Map<Node, readonly string[]>();
135
+ const enterScope = (names: readonly string[], isAFunction = false) => {
136
+ scopes.push({
137
+ names: new Set(names),
138
+ isInAFunction: isAFunction || scopes.at(-1)?.isInAFunction === true,
139
+ });
140
+ };
141
+ const leaveScope = () => {
142
+ scopes.pop();
143
+ };
144
+ const read = (name: string) => {
145
+ if (typePositions.length > 0) {
146
+ return;
147
+ }
148
+ const owner = scopes.findLastIndex(({ names }) => names.has(name));
149
+ const isAFunctionLocal = owner !== -1 && scopes[owner]?.isInAFunction === true;
150
+ if (!isAFunctionLocal) {
151
+ return;
152
+ }
153
+ for (const candidate of open) {
154
+ const isCapturedByCandidate = owner < candidate.depth && name !== candidate.name;
155
+ if (isCapturedByCandidate) {
156
+ candidate.readsAnEnclosingLocal = true;
157
+ }
158
+ }
159
+ };
160
+ const openFunction = (name: string, code: Node) => {
161
+ open.push({ name, code, depth: scopes.length, readsAnEnclosingLocal: false });
162
+ };
163
+ const closeFunction = (code: Node) => {
164
+ const candidate = open.at(-1);
165
+ if (candidate?.code !== code) {
166
+ return;
167
+ }
168
+ open.pop();
169
+ if (!candidate.readsAnEnclosingLocal) {
170
+ named.push({ name: candidate.name, start: code.start, end: code.end, code });
171
+ }
172
+ };
173
+ const enterFunction = (node: ArrowFunctionExpression | FunctionNode) => {
174
+ const { id } = node;
175
+ const isANamedExpression = node.type === "FunctionExpression" && id !== null;
176
+ const ownName = isANamedExpression ? [id.name] : [];
177
+ const implicitBindings =
178
+ node.type === "ArrowFunctionExpression" ? [] : [IMPLICIT_ARGUMENTS, OWN_THIS];
179
+ const hoisted =
180
+ node.body?.type === "BlockStatement"
181
+ ? node.body.body.flatMap((statement) => varNamesIn(statement))
182
+ : [];
183
+ enterScope(
184
+ [
185
+ ...ownName,
186
+ ...implicitBindings,
187
+ ...node.params.flatMap((parameter) => bindingNamesOf(parameter)),
188
+ ...hoisted,
189
+ ],
190
+ true,
191
+ );
192
+ };
193
+ const enterClass = (node: Class) => {
194
+ enterScope(node.id === null ? [] : [node.id.name]);
195
+ };
196
+ const enterTypePosition = (node: Node) => {
197
+ typePositions.push(node);
198
+ };
199
+ const leaveTypePosition = () => {
200
+ typePositions.pop();
201
+ };
202
+ const ignoreKey = (node: { computed: boolean; key: Node }) => {
203
+ if (!node.computed) {
204
+ propertyNames.add(node.key);
205
+ }
206
+ };
207
+ new Visitor({
208
+ FunctionDeclaration(node) {
209
+ const { id: declared, body } = node;
210
+ const isNamedWithBody = declared !== null && body !== null;
211
+ if (isNamedWithBody) {
212
+ openFunction(declared.name, node);
213
+ }
214
+ enterFunction(node);
215
+ },
216
+ "FunctionDeclaration:exit"(node) {
217
+ leaveScope();
218
+ closeFunction(node);
219
+ },
220
+ FunctionExpression: enterFunction,
221
+ "FunctionExpression:exit": leaveScope,
222
+ ArrowFunctionExpression: enterFunction,
223
+ "ArrowFunctionExpression:exit": leaveScope,
224
+ VariableDeclarator(node) {
225
+ const declared = node.id;
226
+ const isNamedFunction = declared.type === "Identifier" && isFunctionAssignedTo(node.init);
227
+ if (isNamedFunction) {
228
+ openFunction(declared.name, node);
229
+ }
230
+ },
231
+ "VariableDeclarator:exit": closeFunction,
232
+ ClassExpression: enterClass,
233
+ "ClassExpression:exit": leaveScope,
234
+ BlockStatement(node) {
235
+ enterScope(node.body.flatMap((statement) => lexicalNamesDeclaredBy(statement)));
236
+ },
237
+ "BlockStatement:exit": leaveScope,
238
+ StaticBlock(node) {
239
+ enterScope([
240
+ ...node.body.flatMap((statement) => lexicalNamesDeclaredBy(statement)),
241
+ ...node.body.flatMap((statement) => varNamesIn(statement)),
242
+ ]);
243
+ },
244
+ "StaticBlock:exit": leaveScope,
245
+ SwitchStatement(node) {
246
+ const [firstCase] = node.cases;
247
+ if (firstCase !== undefined) {
248
+ caseScopes.set(
249
+ firstCase,
250
+ node.cases.flatMap(({ consequent }) =>
251
+ consequent.flatMap((statement) => lexicalNamesDeclaredBy(statement)),
252
+ ),
253
+ );
254
+ }
255
+ },
256
+ SwitchCase(node) {
257
+ const names = caseScopes.get(node);
258
+ if (names !== undefined) {
259
+ enterScope(names);
260
+ }
261
+ },
262
+ "SwitchStatement:exit"(node) {
263
+ if (node.cases.length > 0) {
264
+ leaveScope();
265
+ }
266
+ },
267
+ ForStatement(node) {
268
+ enterScope(lexicalNamesDeclaredBy(node.init));
269
+ },
270
+ "ForStatement:exit": leaveScope,
271
+ ForInStatement(node) {
272
+ enterScope(node.left.type === "VariableDeclaration" ? lexicalNamesDeclaredBy(node.left) : []);
273
+ },
274
+ "ForInStatement:exit": leaveScope,
275
+ ForOfStatement(node) {
276
+ enterScope(node.left.type === "VariableDeclaration" ? lexicalNamesDeclaredBy(node.left) : []);
277
+ },
278
+ "ForOfStatement:exit": leaveScope,
279
+ CatchClause(node) {
280
+ enterScope(bindingNamesOf(node.param));
281
+ },
282
+ "CatchClause:exit": leaveScope,
283
+ TSEnumBody(node) {
284
+ enterScope(
285
+ node.members.flatMap(({ id }) => {
286
+ if (id.type === "Identifier") {
287
+ return [id.name];
288
+ }
289
+ return id.type === "Literal" ? [id.value] : [];
290
+ }),
291
+ );
292
+ },
293
+ "TSEnumBody:exit": leaveScope,
294
+ TSEnumMember(node) {
295
+ propertyNames.add(node.id);
296
+ },
297
+ MemberExpression(node) {
298
+ if (!node.computed) {
299
+ propertyNames.add(node.property);
300
+ }
301
+ },
302
+ Property: ignoreKey,
303
+ MethodDefinition: ignoreKey,
304
+ PropertyDefinition: ignoreKey,
305
+ AccessorProperty: ignoreKey,
306
+ TSAbstractAccessorProperty: ignoreKey,
307
+ TSAbstractMethodDefinition: ignoreKey,
308
+ TSAbstractPropertyDefinition: ignoreKey,
309
+ TSPropertySignature: ignoreKey,
310
+ TSMethodSignature: ignoreKey,
311
+ MetaProperty(node) {
312
+ propertyNames.add(node.meta);
313
+ propertyNames.add(node.property);
314
+ },
315
+ LabeledStatement(node) {
316
+ propertyNames.add(node.label);
317
+ },
318
+ BreakStatement(node) {
319
+ if (node.label !== null) {
320
+ propertyNames.add(node.label);
321
+ }
322
+ },
323
+ ContinueStatement(node) {
324
+ if (node.label !== null) {
325
+ propertyNames.add(node.label);
326
+ }
327
+ },
328
+ TSTypeAnnotation: enterTypePosition,
329
+ "TSTypeAnnotation:exit": leaveTypePosition,
330
+ TSTypeAliasDeclaration: enterTypePosition,
331
+ "TSTypeAliasDeclaration:exit": leaveTypePosition,
332
+ TSInterfaceDeclaration: enterTypePosition,
333
+ "TSInterfaceDeclaration:exit": leaveTypePosition,
334
+ TSTypeParameterDeclaration: enterTypePosition,
335
+ "TSTypeParameterDeclaration:exit": leaveTypePosition,
336
+ TSTypeParameterInstantiation: enterTypePosition,
337
+ "TSTypeParameterInstantiation:exit": leaveTypePosition,
338
+ TSTypeReference: enterTypePosition,
339
+ "TSTypeReference:exit": leaveTypePosition,
340
+ TSTypeQuery: enterTypePosition,
341
+ "TSTypeQuery:exit": leaveTypePosition,
342
+ TSClassImplements: enterTypePosition,
343
+ "TSClassImplements:exit": leaveTypePosition,
344
+ TSFunctionType: enterTypePosition,
345
+ "TSFunctionType:exit": leaveTypePosition,
346
+ TSConstructorType: enterTypePosition,
347
+ "TSConstructorType:exit": leaveTypePosition,
348
+ TSMappedType: enterTypePosition,
349
+ "TSMappedType:exit": leaveTypePosition,
350
+ TSIndexSignature: enterTypePosition,
351
+ "TSIndexSignature:exit": leaveTypePosition,
352
+ TSTypePredicate: enterTypePosition,
353
+ "TSTypePredicate:exit": leaveTypePosition,
354
+ TSImportType: enterTypePosition,
355
+ "TSImportType:exit": leaveTypePosition,
356
+ TSCallSignatureDeclaration: enterTypePosition,
357
+ "TSCallSignatureDeclaration:exit": leaveTypePosition,
358
+ TSConstructSignatureDeclaration: enterTypePosition,
359
+ "TSConstructSignatureDeclaration:exit": leaveTypePosition,
360
+ TSArrayType: enterTypePosition,
361
+ "TSArrayType:exit": leaveTypePosition,
362
+ TSConditionalType: enterTypePosition,
363
+ "TSConditionalType:exit": leaveTypePosition,
364
+ TSDeclareFunction: enterTypePosition,
365
+ "TSDeclareFunction:exit": leaveTypePosition,
366
+ TSEmptyBodyFunctionExpression: enterTypePosition,
367
+ "TSEmptyBodyFunctionExpression:exit": leaveTypePosition,
368
+ TSIndexedAccessType: enterTypePosition,
369
+ "TSIndexedAccessType:exit": leaveTypePosition,
370
+ TSInferType: enterTypePosition,
371
+ "TSInferType:exit": leaveTypePosition,
372
+ TSInterfaceHeritage: enterTypePosition,
373
+ "TSInterfaceHeritage:exit": leaveTypePosition,
374
+ TSIntersectionType: enterTypePosition,
375
+ "TSIntersectionType:exit": leaveTypePosition,
376
+ TSLiteralType: enterTypePosition,
377
+ "TSLiteralType:exit": leaveTypePosition,
378
+ TSNamedTupleMember: enterTypePosition,
379
+ "TSNamedTupleMember:exit": leaveTypePosition,
380
+ TSOptionalType: enterTypePosition,
381
+ "TSOptionalType:exit": leaveTypePosition,
382
+ TSParenthesizedType: enterTypePosition,
383
+ "TSParenthesizedType:exit": leaveTypePosition,
384
+ TSRestType: enterTypePosition,
385
+ "TSRestType:exit": leaveTypePosition,
386
+ TSTemplateLiteralType: enterTypePosition,
387
+ "TSTemplateLiteralType:exit": leaveTypePosition,
388
+ TSThisType: enterTypePosition,
389
+ "TSThisType:exit": leaveTypePosition,
390
+ TSTupleType: enterTypePosition,
391
+ "TSTupleType:exit": leaveTypePosition,
392
+ TSTypeLiteral: enterTypePosition,
393
+ "TSTypeLiteral:exit": leaveTypePosition,
394
+ TSTypeOperator: enterTypePosition,
395
+ "TSTypeOperator:exit": leaveTypePosition,
396
+ TSTypeParameter: enterTypePosition,
397
+ "TSTypeParameter:exit": leaveTypePosition,
398
+ TSUnionType: enterTypePosition,
399
+ "TSUnionType:exit": leaveTypePosition,
400
+ JSXOpeningElement(node) {
401
+ const component = componentRootOf(node.name);
402
+ if (component !== undefined) {
403
+ read(component);
404
+ }
405
+ },
406
+ ThisExpression() {
407
+ read(OWN_THIS);
408
+ },
409
+ Identifier(node) {
410
+ if (!propertyNames.has(node)) {
411
+ read(node.name);
412
+ }
413
+ },
414
+ }).visit(parseSync(path, text, { astType: "ts" }).program);
415
+ return named.toSorted((first, second) => first.start - second.start);
416
+ };
@@ -238,10 +238,9 @@ const inferredType = (
238
238
  );
239
239
  });
240
240
 
241
- const annotationsStillNeeded = <CountingError>(
241
+ const projectsWithoutAnnotations = (
242
242
  projectFile: string,
243
243
  candidates: readonly Effect.Success<ReturnType<typeof candidatesIn>>[number][],
244
- countBaselineViolations: Effect.Effect<ReadonlyMap<string, number>, CountingError>,
245
244
  ) =>
246
245
  Effect.gen(function* () {
247
246
  const candidatesOfSourceFile = Map.groupBy(candidates, (candidate) => candidate.sourceFile);
@@ -257,16 +256,30 @@ const annotationsStillNeeded = <CountingError>(
257
256
  textWithoutAnnotations(sourceFile.text, fileCandidates),
258
257
  ]),
259
258
  );
260
- const needed = new Set<(typeof candidates)[number]>();
261
- const strippedProjects = yield* openTypeScriptProjects(projectFile, sourceTextOverrides);
262
- for (const { checker, sourceFiles } of strippedProjects) {
259
+ const projects = yield* openTypeScriptProjects(projectFile, sourceTextOverrides);
260
+ for (const { sourceFiles } of projects) {
263
261
  for (const { sourceFile } of sourceFiles) {
264
262
  const override = sourceTextOverrides.get(sourceFile.fileName);
265
263
  const isOverrideMissingFromProgram = override !== undefined && override !== sourceFile.text;
266
264
  if (isOverrideMissingFromProgram) {
267
265
  return yield* new SourceOverlayNotApplied({ fileName: sourceFile.fileName });
268
266
  }
269
- const fileCandidates = candidatesOfFile.get(sourceFile.fileName) ?? [];
267
+ }
268
+ }
269
+ return { projects, candidatesOfFile };
270
+ });
271
+
272
+ const annotationsStillNeeded = <CountingError>(
273
+ projectFile: string,
274
+ candidates: readonly Effect.Success<ReturnType<typeof candidatesIn>>[number][],
275
+ countBaselineViolations: Effect.Effect<ReadonlyMap<string, number>, CountingError>,
276
+ ) =>
277
+ Effect.gen(function* () {
278
+ const typeChanging = new Set<(typeof candidates)[number]>();
279
+ const stripped = yield* projectsWithoutAnnotations(projectFile, candidates);
280
+ for (const { checker, sourceFiles } of stripped.projects) {
281
+ for (const { sourceFile } of sourceFiles) {
282
+ const fileCandidates = stripped.candidatesOfFile.get(sourceFile.fileName) ?? [];
270
283
  const annotatable = annotatableNodesByStart(sourceFile);
271
284
  for (const candidate of fileCandidates) {
272
285
  const node = annotatable.get(
@@ -280,18 +293,24 @@ const annotationsStillNeeded = <CountingError>(
280
293
  (yield* typeText(checker, yield* inferredType(checker, node))) !==
281
294
  candidate.annotatedTypeText;
282
295
  if (strippingChangedType) {
283
- needed.add(candidate);
296
+ typeChanging.add(candidate);
284
297
  }
285
298
  }
286
299
  }
287
300
  }
288
- if (needed.size === candidates.length) {
289
- return needed;
301
+ const removable = candidates.filter((candidate) => !typeChanging.has(candidate));
302
+ if (removable.length === 0) {
303
+ return typeChanging;
290
304
  }
305
+ const strippedOfRemovable =
306
+ typeChanging.size === 0
307
+ ? stripped
308
+ : yield* projectsWithoutAnnotations(projectFile, removable);
309
+ const needed = new Set(typeChanging);
291
310
  const remainingBaseline = new Map(yield* countBaselineViolations);
292
- for (const { program, sourceFiles } of strippedProjects) {
311
+ for (const { program, sourceFiles } of strippedOfRemovable.projects) {
293
312
  for (const { sourceFile } of sourceFiles) {
294
- const fileCandidates = candidatesOfFile.get(sourceFile.fileName) ?? [];
313
+ const fileCandidates = strippedOfRemovable.candidatesOfFile.get(sourceFile.fileName) ?? [];
295
314
  const newViolations = (yield* typeScriptViolationsOf(program, sourceFile.fileName)).filter(
296
315
  (violation) => {
297
316
  const key = violationKey(sourceFile.fileName, violation);
@@ -301,7 +320,7 @@ const annotationsStillNeeded = <CountingError>(
301
320
  },
302
321
  );
303
322
  if (newViolations.length > 0) {
304
- for (const candidate of fileCandidates.length > 0 ? fileCandidates : candidates) {
323
+ for (const candidate of fileCandidates.length > 0 ? fileCandidates : removable) {
305
324
  needed.add(candidate);
306
325
  }
307
326
  }
@@ -1,5 +1,10 @@
1
1
  import { Task } from "@sshkeda/task";
2
+ import { Effect } from "effect";
2
3
 
4
+ import { ProjectQueryCachesLive } from "../../shared/provide-project-query-caches.ts";
3
5
  import { fileLayoutViolationsOfEachPackage } from "./internal/check-the-layout-of-each-package.ts";
4
6
 
5
- export const layout = Task.make("layout", fileLayoutViolationsOfEachPackage);
7
+ export const layout = Task.make(
8
+ "layout",
9
+ fileLayoutViolationsOfEachPackage.pipe(Effect.provide(ProjectQueryCachesLive)),
10
+ );
@@ -220,6 +220,15 @@ export class ExportPathMismatch extends Schema.TaggedError<ExportPathMismatch>()
220
220
  }
221
221
  }
222
222
 
223
+ export class PackageEntryNotTypeScript extends Schema.TaggedError<PackageEntryNotTypeScript>()(
224
+ "PackageEntryNotTypeScript",
225
+ { location: Schema.String, field: Schema.String, target: Schema.String },
226
+ ) {
227
+ public override get message() {
228
+ return `${this.field} points to ${this.target}, which is not a TypeScript source file`;
229
+ }
230
+ }
231
+
223
232
  export class RepositoryRootNotFound extends Schema.TaggedError<RepositoryRootNotFound>()(
224
233
  "RepositoryRootNotFound",
225
234
  { directory: Schema.String, reason: Schema.String },
@@ -395,6 +404,7 @@ export class FileLayoutViolations extends Schema.TaggedError<FileLayoutViolation
395
404
  PackageScriptsField,
396
405
  DependencyOutsideRepository,
397
406
  ExportPathMismatch,
407
+ PackageEntryNotTypeScript,
398
408
  UngrantedDocument,
399
409
  UngrantedDirectory,
400
410
  DirectoryGrantOnFile,