@sshkeda/check 4.3.0 → 4.5.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 (22) hide show
  1. package/README.md +3 -1
  2. package/docs/how-to-grant-a-permission.md +4 -2
  3. package/docs/how-to-make-check-pass.md +36 -21
  4. package/package.json +2 -2
  5. package/src/internal/ban-promise-combinators.ts +222 -0
  6. package/src/internal/ban-writes-to-native-prototypes.ts +207 -0
  7. package/src/internal/define-the-lint-plugin-and-configs.ts +4 -1
  8. package/src/internal/resolve-globals-through-constant-aliases.ts +186 -0
  9. package/src/lib/tasks/internal/declare-the-checker-queries-task.ts +2 -0
  10. package/src/lib/tasks/lib/enforce-file-layout/internal/file-layout-errors.ts +10 -0
  11. package/src/lib/tasks/lib/enforce-file-layout/internal/find-export-path-mismatches.ts +51 -18
  12. package/src/lib/tasks/lib/enforce-file-layout/internal/find-file-layout-violations.ts +2 -0
  13. package/src/lib/tasks/lib/enforce-file-types/index.ts +4 -1
  14. package/src/lib/tasks/lib/refuse-disable-directives/internal/find-disable-directives.ts +69 -20
  15. package/src/lib/tasks/lib/refuse-promise-chains/index.ts +1 -0
  16. package/src/lib/tasks/lib/refuse-promise-chains/internal/find-promise-chains.ts +141 -0
  17. package/src/lib/tasks/lib/refuse-promise-chains/internal/promise-chain-errors.ts +21 -0
  18. package/src/lib/tasks/lib/type-check-with-bun-check/index.ts +2 -3
  19. package/src/lib/tasks/lib/type-check-with-bun-check/internal/check-types-with-bun-check.ts +21 -5
  20. package/src/lib/tasks/shared/print-failures-and-keep-detail-in-the-trace.ts +1 -1
  21. package/src/lib/tasks/shared/watch-the-typescript-api-process.ts +47 -20
  22. package/src/shared/lint-rule-messages-and-patterns.ts +11 -4
@@ -0,0 +1,186 @@
1
+ import type { Definition, ESTree, Scope, SourceCode, Variable } from "@oxlint/plugins";
2
+
3
+ import {
4
+ constantValue,
5
+ memberName,
6
+ propertyKeyName,
7
+ staticKeyName,
8
+ unwrappedExpression,
9
+ } from "./resolve-what-an-expression-imports.ts";
10
+
11
+ export const GLOBAL_CONTAINERS: ReadonlySet<string> = new Set([
12
+ "global",
13
+ "globalThis",
14
+ "self",
15
+ "window",
16
+ ]);
17
+
18
+ export const staticMemberKey = (node: ESTree.MemberExpression, sourceCode: SourceCode) => {
19
+ const name = memberName(node);
20
+ const isUnresolvedComputedKey = name === undefined && node.computed;
21
+ return isUnresolvedComputedKey ? staticKeyName(constantValue(node.property, sourceCode)) : name;
22
+ };
23
+
24
+ const TYPE_DECLARATIONS: ReadonlySet<string> = new Set([
25
+ "TSInterfaceDeclaration",
26
+ "TSTypeAliasDeclaration",
27
+ "TSTypeParameter",
28
+ ]);
29
+
30
+ const isTypeOnlyDefinition = (definition: Definition) => {
31
+ const { node, parent } = definition;
32
+ const isTypeOnlySpecifier = node.type === "ImportSpecifier" && node.importKind === "type";
33
+ const isTypeOnlyImport = parent?.type === "ImportDeclaration" && parent.importKind === "type";
34
+ return TYPE_DECLARATIONS.has(node.type) || isTypeOnlySpecifier || isTypeOnlyImport;
35
+ };
36
+
37
+ const bindingVisibleFrom = (
38
+ scope: Scope,
39
+ name: string,
40
+ ignoresTypeOnlyBindings: boolean,
41
+ ): { readonly variable: Variable; readonly definitions: readonly Definition[] } | undefined => {
42
+ const variable = scope.set.get(name);
43
+ const allDefinitions = variable?.defs ?? [];
44
+ const definitions = ignoresTypeOnlyBindings
45
+ ? allDefinitions.filter((definition) => !isTypeOnlyDefinition(definition))
46
+ : allDefinitions;
47
+ const isTypeOnlyBinding = allDefinitions.length > 0 && definitions.length === 0;
48
+ const isVisibleBinding = variable !== undefined && !isTypeOnlyBinding;
49
+ if (isVisibleBinding) {
50
+ return { variable, definitions };
51
+ }
52
+ return scope.upper === null
53
+ ? undefined
54
+ : bindingVisibleFrom(scope.upper, name, ignoresTypeOnlyBindings);
55
+ };
56
+
57
+ const bindingOf = (node: ESTree.Node, sourceCode: SourceCode, ignoresTypeOnlyBindings: boolean) =>
58
+ node.type === "Identifier"
59
+ ? bindingVisibleFrom(sourceCode.getScope(node), node.name, ignoresTypeOnlyBindings)
60
+ : undefined;
61
+
62
+ const isGlobalBinding = (
63
+ node: ESTree.Node,
64
+ sourceCode: SourceCode,
65
+ ignoresTypeOnlyBindings: boolean,
66
+ ) => {
67
+ const binding = bindingOf(node, sourceCode, ignoresTypeOnlyBindings);
68
+ return binding === undefined || binding.definitions.length === 0;
69
+ };
70
+
71
+ const onlyDefinitionOf = (
72
+ node: ESTree.Node,
73
+ sourceCode: SourceCode,
74
+ ignoresTypeOnlyBindings: boolean,
75
+ ) => {
76
+ const binding = bindingOf(node, sourceCode, ignoresTypeOnlyBindings);
77
+ const variable = binding?.variable;
78
+ const definitions = binding?.definitions ?? [];
79
+ const [definition] = definitions;
80
+ const isOnlyDefinition =
81
+ variable !== undefined && definition !== undefined && definitions.length === 1;
82
+ return isOnlyDefinition ? { variable, definition } : undefined;
83
+ };
84
+
85
+ const constantAlias = (
86
+ node: ESTree.Node,
87
+ sourceCode: SourceCode,
88
+ ignoresTypeOnlyBindings: boolean,
89
+ ) => {
90
+ const defined = onlyDefinitionOf(node, sourceCode, ignoresTypeOnlyBindings);
91
+ const declarator = defined?.definition.node;
92
+ const isConstantDeclarator =
93
+ declarator?.type === "VariableDeclarator" &&
94
+ declarator.parent.type === "VariableDeclaration" &&
95
+ declarator.parent.kind === "const";
96
+ const value = isConstantDeclarator ? declarator.init : null;
97
+ const isConstantWithAValue = defined !== undefined && isConstantDeclarator && value !== null;
98
+ if (!isConstantWithAValue) {
99
+ return;
100
+ }
101
+ const { variable, definition } = defined;
102
+ if (declarator.id.type === "Identifier") {
103
+ return { variable, value, key: undefined };
104
+ }
105
+ const property = definition.name.parent;
106
+ const isDestructuredByKey =
107
+ property.type === "Property" &&
108
+ property.value === definition.name &&
109
+ property.parent === declarator.id;
110
+ const key = isDestructuredByKey ? propertyKeyName(property) : undefined;
111
+ return key === undefined ? undefined : { variable, value, key };
112
+ };
113
+
114
+ const declaredClass = (
115
+ node: ESTree.Node,
116
+ sourceCode: SourceCode,
117
+ ignoresTypeOnlyBindings: boolean,
118
+ ) => {
119
+ const defined = onlyDefinitionOf(node, sourceCode, ignoresTypeOnlyBindings);
120
+ const declared = defined?.definition.node;
121
+ const isDeclaredClass =
122
+ (declared?.type === "ClassDeclaration" || declared?.type === "ClassExpression") &&
123
+ defined !== undefined;
124
+ return isDeclaredClass ? { variable: defined.variable, declared } : undefined;
125
+ };
126
+
127
+ export const globalValueOf = <Value>(
128
+ expression: ESTree.Node,
129
+ sourceCode: SourceCode,
130
+ resolver: {
131
+ readonly global: (name: string) => Value | undefined;
132
+ readonly member: (owner: Value | undefined, key: string) => Value | undefined;
133
+ readonly subclass?: (
134
+ superClass: Value | undefined,
135
+ declaration: ESTree.Class,
136
+ ) => Value | undefined;
137
+ readonly ignoresTypeOnlyBindings?: boolean;
138
+ },
139
+ seen: ReadonlySet<Variable> = new Set(),
140
+ ): Value | undefined => {
141
+ const node = unwrappedExpression(expression);
142
+ if (node.type === "ChainExpression") {
143
+ return globalValueOf(node.expression, sourceCode, resolver, seen);
144
+ }
145
+ if (node.type === "MemberExpression") {
146
+ const key = staticMemberKey(node, sourceCode);
147
+ return key === undefined
148
+ ? undefined
149
+ : resolver.member(globalValueOf(node.object, sourceCode, resolver, seen), key);
150
+ }
151
+ const isClass = node.type === "ClassDeclaration" || node.type === "ClassExpression";
152
+ if (isClass) {
153
+ const { subclass } = resolver;
154
+ const { superClass } = node;
155
+ const isSubclassOfAValue = subclass !== undefined && superClass !== null;
156
+ return isSubclassOfAValue
157
+ ? subclass(globalValueOf(superClass, sourceCode, resolver, seen), node)
158
+ : undefined;
159
+ }
160
+ if (node.type !== "Identifier") {
161
+ return;
162
+ }
163
+ const ignoresTypeOnlyBindings = resolver.ignoresTypeOnlyBindings === true;
164
+ if (isGlobalBinding(node, sourceCode, ignoresTypeOnlyBindings)) {
165
+ return resolver.global(node.name);
166
+ }
167
+ const alias = constantAlias(node, sourceCode, ignoresTypeOnlyBindings);
168
+ const isUnseenAlias = alias !== undefined && !seen.has(alias.variable);
169
+ if (isUnseenAlias) {
170
+ const value = globalValueOf(
171
+ alias.value,
172
+ sourceCode,
173
+ resolver,
174
+ new Set([...seen, alias.variable]),
175
+ );
176
+ return alias.key === undefined ? value : resolver.member(value, alias.key);
177
+ }
178
+ const declared =
179
+ resolver.subclass === undefined
180
+ ? undefined
181
+ : declaredClass(node, sourceCode, ignoresTypeOnlyBindings);
182
+ const isUnseenClass = declared !== undefined && !seen.has(declared.variable);
183
+ return isUnseenClass
184
+ ? globalValueOf(declared.declared, sourceCode, resolver, new Set([...seen, declared.variable]))
185
+ : undefined;
186
+ };
@@ -11,6 +11,7 @@ import { findIndexReExportViolations } from "../lib/judge-index-re-exports/index
11
11
  import { findExportPlacementViolations } from "../lib/place-exports-in-the-narrowest-directory/index.ts";
12
12
  import { findErrorMappingsToDone } from "../lib/refuse-error-mappings-that-end-streams/index.ts";
13
13
  import { findUnobservedForkFailures } from "../lib/refuse-forks-whose-failures-nothing-observes/index.ts";
14
+ import { findPromiseChains } from "../lib/refuse-promise-chains/index.ts";
14
15
  import { findServiceLayerViolations } from "../lib/require-separate-service-layers/index.ts";
15
16
  import { inEachPackage } from "../shared/check-each-nested-package.ts";
16
17
  import { lintConfigFile } from "../shared/declare-lint-config-task.ts";
@@ -36,6 +37,7 @@ export const checkerQueries = Task.make({
36
37
  "layer-provides": findLayerProvidesOutsideProgramStarts,
37
38
  "error-mappings": findErrorMappingsToDone,
38
39
  "fork-failures": findUnobservedForkFailures,
40
+ "promise-chains": findPromiseChains,
39
41
  "re-exports": findIndexReExportViolations,
40
42
  }),
41
43
  ),
@@ -225,6 +225,15 @@ export class PackageEntryNotTypeScript extends Schema.TaggedError<PackageEntryNo
225
225
  }
226
226
  }
227
227
 
228
+ export class PackageExportPattern extends Schema.TaggedError<PackageExportPattern>()(
229
+ "PackageExportPattern",
230
+ { location: Schema.String, field: Schema.String, pattern: Schema.String },
231
+ ) {
232
+ public override get message() {
233
+ return `${this.field} contains package export pattern "${this.pattern}"`;
234
+ }
235
+ }
236
+
228
237
  export class RepositoryRootNotFound extends Schema.TaggedError<RepositoryRootNotFound>()(
229
238
  "RepositoryRootNotFound",
230
239
  { directory: Schema.String, reason: Schema.String },
@@ -400,6 +409,7 @@ export class FileLayoutViolations extends Schema.TaggedError<FileLayoutViolation
400
409
  DependencyOutsideRepository,
401
410
  ExportPathMismatch,
402
411
  PackageEntryNotTypeScript,
412
+ PackageExportPattern,
403
413
  UngrantedDocument,
404
414
  UngrantedDirectory,
405
415
  DirectoryGrantOnFile,
@@ -6,6 +6,7 @@ import {
6
6
  ExportPathMismatch,
7
7
  moduleDirectoryNamedBy,
8
8
  PackageEntryNotTypeScript,
9
+ PackageExportPattern,
9
10
  } from "./file-layout-errors.ts";
10
11
 
11
12
  const ROOT_SUBPATH = ".";
@@ -16,6 +17,7 @@ const CODE_FILE = /\.[cm]?[jt]sx?$/u;
16
17
  const FILE_EXTENSION = /\.[^./]+$/u;
17
18
  const INDEX_FILE = /^index\.tsx?$/u;
18
19
  const PACKAGE_PATTERN_WILDCARD = "*";
20
+ const DIRECTORY_MAPPING_END = "/";
19
21
  const ENTRY_FIELDS = ["main", "module", "types", "typings"] as const;
20
22
  const PROPERTY_NAME = /^[A-Za-z_$][\w$]*$/u;
21
23
  const isJsonObject = Schema.is(JSON_OBJECT);
@@ -42,6 +44,12 @@ const targetsUnderEveryCondition = (
42
44
  );
43
45
  };
44
46
 
47
+ const isPackageExportPattern = (path: string) =>
48
+ path.includes(PACKAGE_PATTERN_WILDCARD) || path.endsWith(DIRECTORY_MAPPING_END);
49
+
50
+ const isPackageExportPatternTarget = (target: string) =>
51
+ isPackageExportPattern(target.replace(QUERY_OR_FRAGMENT, ""));
52
+
45
53
  const subpathsWithTheirFields = (exports: Schema.Json) => {
46
54
  const isSubpathMap =
47
55
  isJsonObject(exports) && Object.keys(exports).some((key) => key.startsWith(ROOT_SUBPATH));
@@ -50,8 +58,39 @@ const subpathsWithTheirFields = (exports: Schema.Json) => {
50
58
  subpath,
51
59
  field: fieldWithKey("exports", subpath),
52
60
  value,
61
+ isPatternKey: isPackageExportPattern(subpath),
53
62
  }))
54
- : [{ subpath: ROOT_SUBPATH, field: "exports", value: exports }];
63
+ : [{ subpath: ROOT_SUBPATH, field: "exports", value: exports, isPatternKey: false }];
64
+ };
65
+
66
+ const namedExportTargets = (exports: Schema.Json) =>
67
+ subpathsWithTheirFields(exports).flatMap(({ subpath, field, value, isPatternKey }) =>
68
+ isPatternKey
69
+ ? []
70
+ : targetsUnderEveryCondition(field, value)
71
+ .filter(({ target }) => !isPackageExportPatternTarget(target))
72
+ .map(({ field: targetField, target }) => ({ subpath, field: targetField, target })),
73
+ );
74
+
75
+ export const packageExportPatterns = (path: string, manifest: typeof JSON_OBJECT.Type) => {
76
+ const exports = manifest["exports"];
77
+ if (exports === undefined) {
78
+ return [];
79
+ }
80
+ return subpathsWithTheirFields(exports).flatMap(({ subpath, field, value, isPatternKey }) => {
81
+ const targets = targetsUnderEveryCondition(field, value);
82
+ if (isPatternKey) {
83
+ return targets.length > 0
84
+ ? [new PackageExportPattern({ location: path, field, pattern: subpath })]
85
+ : [];
86
+ }
87
+ return targets
88
+ .filter(({ target }) => isPackageExportPatternTarget(target))
89
+ .map(
90
+ ({ field: targetField, target }) =>
91
+ new PackageExportPattern({ location: path, field: targetField, pattern: target }),
92
+ );
93
+ });
55
94
  };
56
95
 
57
96
  const isIndexOfTheDirectoryTheSubpathNames = (subpath: string, target: string) => {
@@ -76,18 +115,16 @@ export const exportPathMismatches = (path: string, manifest: typeof JSON_OBJECT.
76
115
  if (exports === undefined) {
77
116
  return [];
78
117
  }
79
- return subpathsWithTheirFields(exports).flatMap(({ subpath, field, value }) =>
80
- targetsUnderEveryCondition(field, value)
81
- .filter(
82
- ({ target }) =>
83
- isTypeScriptSourceFile(target.replace(QUERY_OR_FRAGMENT, "")) &&
84
- !isIndexOfTheDirectoryTheSubpathNames(subpath, target),
85
- )
86
- .map(
87
- ({ field: conditionField, target }) =>
88
- new ExportPathMismatch({ location: path, field: conditionField, target, subpath }),
89
- ),
90
- );
118
+ return namedExportTargets(exports)
119
+ .filter(
120
+ ({ subpath, target }) =>
121
+ isTypeScriptSourceFile(target.replace(QUERY_OR_FRAGMENT, "")) &&
122
+ !isIndexOfTheDirectoryTheSubpathNames(subpath, target),
123
+ )
124
+ .map(
125
+ ({ subpath, field, target }) =>
126
+ new ExportPathMismatch({ location: path, field, target, subpath }),
127
+ );
91
128
  };
92
129
 
93
130
  const isCodeOtherThanTypeScriptSource = (target: string) => {
@@ -104,11 +141,7 @@ export const packageEntriesNotTypeScript = (path: string, manifest: typeof JSON_
104
141
  const target = manifest[field];
105
142
  return typeof target === "string" ? [{ field, target }] : [];
106
143
  }),
107
- ...(exports === undefined
108
- ? []
109
- : subpathsWithTheirFields(exports).flatMap(({ field, value }) =>
110
- targetsUnderEveryCondition(field, value),
111
- )),
144
+ ...(exports === undefined ? [] : namedExportTargets(exports)),
112
145
  ]
113
146
  .filter(({ target }) => isCodeOtherThanTypeScriptSource(target))
114
147
  .map(({ field, target }) => new PackageEntryNotTypeScript({ location: path, field, target }));
@@ -96,6 +96,7 @@ import {
96
96
  import {
97
97
  exportPathMismatches,
98
98
  packageEntriesNotTypeScript,
99
+ packageExportPatterns,
99
100
  } from "./find-export-path-mismatches.ts";
100
101
  import {
101
102
  directoriesOutsideModuleLayoutAmong,
@@ -459,6 +460,7 @@ export const manifestViolations = (
459
460
  ...(yield* dependenciesOutsideRepository(path, manifest.success, repository)),
460
461
  ...packageEntriesNotTypeScript(path, manifest.success),
461
462
  ...exportPathMismatches(path, manifest.success),
463
+ ...packageExportPatterns(path, manifest.success),
462
464
  ];
463
465
  });
464
466
 
@@ -1,10 +1,13 @@
1
1
  import { Task } from "@sshkeda/task";
2
2
  import { Effect } from "effect";
3
3
 
4
+ import { lintConfigFile } from "../../shared/declare-lint-config-task.ts";
4
5
  import { ProjectQueryCachesLive } from "../../shared/provide-project-query-caches.ts";
5
6
  import { fileTypeViolationsOfEachPackage } from "./internal/find-file-type-violations.ts";
6
7
 
7
8
  export const fileTypes = Task.make({
8
9
  name: "file-types",
9
- run: fileTypeViolationsOfEachPackage.pipe(Effect.provide(ProjectQueryCachesLive)),
10
+ run: Effect.andThen(lintConfigFile, fileTypeViolationsOfEachPackage).pipe(
11
+ Effect.provide(ProjectQueryCachesLive),
12
+ ),
10
13
  });
@@ -1,10 +1,17 @@
1
1
  import { Array as Arrays, Effect, FileSystem, Path, Result } from "effect";
2
2
  import { parseSync } from "oxc-parser";
3
+ import type { Comment } from "oxc-parser";
3
4
 
4
5
  import { FORMAT_CONFIG_FILE } from "../../../../../shared/config-file-names.ts";
5
- import { isDirective } from "../../../../../shared/lint-rule-messages-and-patterns.ts";
6
+ import {
7
+ isDirective,
8
+ isTypeScriptSuppression,
9
+ TYPESCRIPT_NO_CHECK,
10
+ } from "../../../../../shared/lint-rule-messages-and-patterns.ts";
11
+ import { isDeclarationFile } from "../../../shared/classify-files-by-role.ts";
6
12
  import { lineNumbersIn, lineOfTheFirstLabel } from "../../../shared/count-the-line-of-an-offset.ts";
7
- import { lintedFiles } from "../../../shared/list-linted-files.ts";
13
+ import { scriptFiles } from "../../../shared/list-linted-files.ts";
14
+ import { ownedFilesAmong } from "../../../shared/list-owned-files.ts";
8
15
  import { isFormatConfigTextRefusedIn } from "../../../shared/parse-config-files-that-import-from-check.ts";
9
16
  import { quietViolations } from "../../../shared/print-failures-and-keep-detail-in-the-trace.ts";
10
17
  import { SourceFileUnparsable } from "../../../shared/project-config-and-tool-errors.ts";
@@ -15,13 +22,34 @@ import {
15
22
  SourceFileUnreadable,
16
23
  } from "./disable-directive-errors.ts";
17
24
 
18
- export const disableDirectivesIn = (file: string, directory = ".") =>
25
+ const LEADING_SLASHES = /^\/+/u;
26
+
27
+ const LINE_COMMENT = "Line";
28
+
29
+ const sourceTextOf = (file: string, directory: string) =>
19
30
  Effect.gen(function* () {
20
31
  const fileSystem = yield* FileSystem.FileSystem;
21
32
  const path = yield* Path.Path;
22
- const text = yield* fileSystem
33
+ return yield* fileSystem
23
34
  .readFileString(path.isAbsolute(file) ? file : path.join(directory, file))
24
35
  .pipe(Effect.mapError((error) => new SourceFileUnreadable({ file, reason: error.message })));
36
+ });
37
+
38
+ const directivesAmong = (file: string, text: string, comments: readonly Comment[]) => {
39
+ const lineAt = lineNumbersIn(text);
40
+ return comments.map(
41
+ (comment) =>
42
+ new DisableDirective({
43
+ file,
44
+ line: lineAt(comment.start),
45
+ directive: comment.value.replace(LEADING_SLASHES, "").trim(),
46
+ }),
47
+ );
48
+ };
49
+
50
+ export const disableDirectivesIn = (file: string, directory = ".") =>
51
+ Effect.gen(function* () {
52
+ const text = yield* sourceTextOf(file, directory);
25
53
  const parsed = parseSync(file, text);
26
54
  if (parsed.errors.length > 0) {
27
55
  return parsed.errors.map(
@@ -33,30 +61,51 @@ export const disableDirectivesIn = (file: string, directory = ".") =>
33
61
  }),
34
62
  );
35
63
  }
36
- const lineAt = lineNumbersIn(text);
37
- return parsed.comments
38
- .filter((comment) => isDirective(comment.value))
39
- .map(
40
- (comment) =>
41
- new DisableDirective({
42
- file,
43
- line: lineAt(comment.start),
44
- directive: comment.value.trim(),
45
- }),
46
- );
64
+ return directivesAmong(
65
+ file,
66
+ text,
67
+ parsed.comments.filter((comment) => isDirective(comment.value)),
68
+ );
69
+ });
70
+
71
+ const typeScriptDirectivesIn = (file: string, directory: string) =>
72
+ Effect.gen(function* () {
73
+ const text = yield* sourceTextOf(file, directory);
74
+ const parsed = parseSync(file, text);
75
+ if (parsed.errors.length > 0) {
76
+ return [];
77
+ }
78
+ const firstStatementStart = parsed.program.body[0]?.start ?? text.length;
79
+ return directivesAmong(
80
+ file,
81
+ text,
82
+ parsed.comments.filter((comment) => {
83
+ const isLeadingLineComment =
84
+ comment.type === LINE_COMMENT && comment.end <= firstStatementStart;
85
+ const isNoCheck = isLeadingLineComment && TYPESCRIPT_NO_CHECK.test(comment.value);
86
+ return isNoCheck || isTypeScriptSuppression(comment.value);
87
+ }),
88
+ );
47
89
  });
48
90
 
49
91
  export const findDisableDirectivesInLintedFilesOf = (directory: string) =>
50
92
  Effect.gen(function* () {
51
93
  const path = yield* Path.Path;
52
94
  const isFormatConfigRefused = yield* isFormatConfigTextRefusedIn(directory);
53
- const files = (yield* lintedFiles(path.join(directory, TYPESCRIPT_PROJECT_FILE))).filter(
54
- (file) => !isFormatConfigRefused || file !== FORMAT_CONFIG_FILE,
95
+ const scripts = yield* scriptFiles(path.join(directory, TYPESCRIPT_PROJECT_FILE));
96
+ const owned = yield* ownedFilesAmong(directory, scripts);
97
+ const ownedFiles = new Set(owned);
98
+ const files = owned.filter((file) => !isFormatConfigRefused || file !== FORMAT_CONFIG_FILE);
99
+ const generatedSources = scripts.filter(
100
+ (file) => !ownedFiles.has(file) && !isDeclarationFile(file),
55
101
  );
56
102
  const scans = yield* Effect.forEach(
57
- files,
58
- (file) =>
59
- disableDirectivesIn(file, directory).pipe(
103
+ [
104
+ ...files.map((file) => disableDirectivesIn(file, directory)),
105
+ ...generatedSources.map((file) => typeScriptDirectivesIn(file, directory)),
106
+ ],
107
+ (scan) =>
108
+ scan.pipe(
60
109
  Effect.map(Result.succeed),
61
110
  Effect.catchTag("SourceFileUnreadable", (unscanned) =>
62
111
  Effect.succeed(Result.fail(unscanned)),
@@ -0,0 +1 @@
1
+ export { findPromiseChains } from "./internal/find-promise-chains.ts";
@@ -0,0 +1,141 @@
1
+ import { Effect } from "effect";
2
+ import type { Node, SourceFile } from "typescript/unstable/ast";
3
+ import {
4
+ isElementAccessExpression,
5
+ isPropertyAccessExpression,
6
+ isStringLiteralLikeNode,
7
+ } from "typescript/unstable/ast/is";
8
+ import { isErrorType, SignatureKind, TypeFlags } from "typescript/unstable/async";
9
+ import type { Checker, Type } from "typescript/unstable/async";
10
+
11
+ import {
12
+ callsIn,
13
+ CONCURRENT_TYPESCRIPT_REQUESTS,
14
+ nodePosition,
15
+ typeMembers,
16
+ typeScriptRequest,
17
+ } from "../../../shared/query-the-typescript-project.ts";
18
+ import type { openTypeScriptProjects } from "../../../shared/query-the-typescript-project.ts";
19
+ import { withoutWrappers } from "../../../shared/read-piped-steps-through-wrappers.ts";
20
+ import { PromiseChained, PromiseChainsRefused } from "./promise-chain-errors.ts";
21
+
22
+ const THEN = "then";
23
+ const CHAINING_METHODS: ReadonlySet<string> = new Set([THEN, "catch", "finally"]);
24
+
25
+ const memberCalledBy = (callee: Node) => {
26
+ if (isPropertyAccessExpression(callee)) {
27
+ return { receiver: callee.expression, key: callee.name };
28
+ }
29
+ if (!isElementAccessExpression(callee)) {
30
+ return;
31
+ }
32
+ const key = callee.argumentExpression;
33
+ return isStringLiteralLikeNode(key) ? { receiver: callee.expression, key } : undefined;
34
+ };
35
+
36
+ const hasCallableThen = (checker: Checker, member: Type) =>
37
+ Effect.gen(function* () {
38
+ const thenProperty = yield* typeScriptRequest("read a then property", () =>
39
+ checker.getPropertyOfType(member, THEN),
40
+ );
41
+ if (thenProperty === undefined) {
42
+ return false;
43
+ }
44
+ const thenType = yield* typeScriptRequest("read the type of a then property", () =>
45
+ checker.getTypeOfSymbol(thenProperty),
46
+ );
47
+ const thenTypes = thenType === undefined ? [] : yield* typeMembers(thenType);
48
+ const signatures = yield* Effect.forEach(thenTypes, (thenMember) =>
49
+ typeScriptRequest("read the signatures of a then property", () =>
50
+ checker.getSignaturesOfType(thenMember, SignatureKind.Call),
51
+ ),
52
+ );
53
+ return signatures.some((memberSignatures) => memberSignatures.length > 0);
54
+ });
55
+
56
+ const isThenable = (checker: Checker, receiver: Type) =>
57
+ Effect.gen(function* () {
58
+ const isUnknown = (receiver.flags & TypeFlags.AnyOrUnknown) !== 0 || isErrorType(receiver);
59
+ if (isUnknown) {
60
+ return false;
61
+ }
62
+ const apparent = yield* typeScriptRequest("read the apparent type of a receiver", () =>
63
+ checker.getApparentType(receiver),
64
+ );
65
+ const members = apparent === undefined ? [] : yield* typeMembers(apparent);
66
+ const thenables = yield* Effect.forEach(members, (member) => hasCallableThen(checker, member));
67
+ return thenables.some(Boolean);
68
+ });
69
+
70
+ const chainedCallsIn = (sourceFile: SourceFile) =>
71
+ callsIn(sourceFile).flatMap((call) => {
72
+ const member = memberCalledBy(withoutWrappers(call.expression));
73
+ const isChaining = member !== undefined && CHAINING_METHODS.has(member.key.text);
74
+ return isChaining ? [member] : [];
75
+ });
76
+
77
+ const projectViolations = (
78
+ checker: Checker,
79
+ sourceFiles: readonly { readonly sourceFile: SourceFile; readonly displayName: string }[],
80
+ ) =>
81
+ Effect.gen(function* () {
82
+ const candidates = sourceFiles.flatMap(({ sourceFile, displayName }) => {
83
+ const chained = chainedCallsIn(sourceFile);
84
+ return chained.length === 0 ? [] : [{ sourceFile, displayName, chained }];
85
+ });
86
+ const files = yield* Effect.forEach(
87
+ candidates,
88
+ ({ sourceFile, displayName, chained }) =>
89
+ typeScriptRequest("read the types of chained receivers", () =>
90
+ checker.getTypeAtLocation(chained.map(({ receiver }) => receiver)),
91
+ ).pipe(Effect.map((types) => ({ sourceFile, displayName, chained, types }))),
92
+ { concurrency: CONCURRENT_TYPESCRIPT_REQUESTS },
93
+ );
94
+ const distinctTypes = [
95
+ ...new Map(
96
+ files.flatMap(({ types }) =>
97
+ types.flatMap((type) => (type === undefined ? [] : [[type.id, type] as const])),
98
+ ),
99
+ ).values(),
100
+ ];
101
+ const thenables = yield* Effect.forEach(distinctTypes, (type) => isThenable(checker, type), {
102
+ concurrency: CONCURRENT_TYPESCRIPT_REQUESTS,
103
+ });
104
+ const thenableTypeIds = new Set(
105
+ distinctTypes.flatMap((type, index) => (thenables[index] === true ? [type.id] : [])),
106
+ );
107
+ return files.flatMap(({ sourceFile, displayName, chained, types }) =>
108
+ chained
109
+ .filter((_member, index) => {
110
+ const type = types[index];
111
+ return type !== undefined && thenableTypeIds.has(type.id);
112
+ })
113
+ .toSorted((left, right) => left.key.pos - right.key.pos)
114
+ .map(({ key }) => {
115
+ const { line, column } = nodePosition(sourceFile, key);
116
+ return new PromiseChained({
117
+ location: `${displayName}:${line}:${column}`,
118
+ method: key.text,
119
+ });
120
+ }),
121
+ );
122
+ });
123
+
124
+ export const findPromiseChains = <OpeningError, OpeningRequirement>(
125
+ _projectFile: string,
126
+ openedProjects: Effect.Effect<
127
+ Effect.Success<ReturnType<typeof openTypeScriptProjects>>,
128
+ OpeningError,
129
+ OpeningRequirement
130
+ >,
131
+ ) =>
132
+ Effect.gen(function* () {
133
+ const violationsOfEachProject = yield* Effect.forEach(
134
+ yield* openedProjects,
135
+ ({ checker, sourceFiles }) => projectViolations(checker, sourceFiles),
136
+ );
137
+ const violations = violationsOfEachProject.flat();
138
+ if (violations.length > 0) {
139
+ return yield* new PromiseChainsRefused({ violations });
140
+ }
141
+ });
@@ -0,0 +1,21 @@
1
+ import { Schema } from "effect";
2
+
3
+ import { listedViolations } from "../../../../../shared/format-reported-failures.ts";
4
+
5
+ export class PromiseChained extends Schema.TaggedError<PromiseChained>()("PromiseChained", {
6
+ location: Schema.String,
7
+ method: Schema.String,
8
+ }) {
9
+ public override get message() {
10
+ return `${this.method} is called on a Promise`;
11
+ }
12
+ }
13
+
14
+ export class PromiseChainsRefused extends Schema.TaggedError<PromiseChainsRefused>()(
15
+ "PromiseChainsRefused",
16
+ { violations: Schema.Array(PromiseChained) },
17
+ ) {
18
+ public override get message() {
19
+ return listedViolations(this.violations);
20
+ }
21
+ }
@@ -1,11 +1,10 @@
1
1
  import { Task } from "@sshkeda/task";
2
2
  import { Effect } from "effect";
3
3
 
4
- import { inEachPackage } from "../../shared/check-each-nested-package.ts";
5
4
  import { typeScriptConfig } from "../../shared/declare-typescript-config-task.ts";
6
- import { checkTypesWithBunCheckIn } from "./internal/check-types-with-bun-check.ts";
5
+ import { typesCheckedInEachPackage } from "./internal/check-types-with-bun-check.ts";
7
6
 
8
7
  export const typeCheck = Task.make({
9
8
  name: "type-check",
10
- run: Effect.andThen(typeScriptConfig, inEachPackage("type-check", checkTypesWithBunCheckIn)),
9
+ run: Effect.andThen(typeScriptConfig, typesCheckedInEachPackage),
11
10
  });