@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
@@ -1,14 +1,22 @@
1
1
  import { Schema } from "effect";
2
2
 
3
+ import { isTypeScriptSourceFile } from "../../../shared/classify-files-by-role.ts";
3
4
  import { JSON_OBJECT } from "../../../shared/read-package-manifest-object.ts";
4
- import { ExportPathMismatch, moduleDirectoryNamedBy } from "./file-layout-errors.ts";
5
+ import {
6
+ ExportPathMismatch,
7
+ moduleDirectoryNamedBy,
8
+ PackageEntryNotTypeScript,
9
+ } from "./file-layout-errors.ts";
5
10
 
6
11
  const ROOT_SUBPATH = ".";
7
12
  const RELATIVE_PREFIX = "./";
8
13
  const QUERY_OR_FRAGMENT = /[?#].*$/u;
9
14
  const NOT_A_DIRECTORY_NAME: ReadonlySet<string> = new Set(["", ".", ".."]);
10
15
  const CODE_FILE = /\.[cm]?[jt]sx?$/u;
11
- const INDEX_FILE = /^index\.(?:d\.)?[cm]?[jt]sx?$/u;
16
+ const FILE_EXTENSION = /\.[^./]+$/u;
17
+ const INDEX_FILE = /^index\.tsx?$/u;
18
+ const PACKAGE_PATTERN_WILDCARD = "*";
19
+ const ENTRY_FIELDS = ["main", "module", "types", "typings"] as const;
12
20
  const PROPERTY_NAME = /^[A-Za-z_$][\w$]*$/u;
13
21
  const isJsonObject = Schema.is(JSON_OBJECT);
14
22
  const isJsonArray = Schema.is(Schema.Array(Schema.Json));
@@ -50,16 +58,16 @@ const isIndexOfTheDirectoryTheSubpathNames = (subpath: string, target: string) =
50
58
  const relativeTarget = target.startsWith(RELATIVE_PREFIX)
51
59
  ? target.slice(RELATIVE_PREFIX.length)
52
60
  : target;
53
- const [sourceOrBuildDirectory = "", ...insideTheSourceOrBuildDirectory] = relativeTarget
61
+ const [sourceDirectory = "", ...insideTheSourceDirectory] = relativeTarget
54
62
  .replace(QUERY_OR_FRAGMENT, "")
55
63
  .split("/");
56
- const fileName = insideTheSourceOrBuildDirectory.at(-1);
64
+ const fileName = insideTheSourceDirectory.at(-1);
57
65
  const namedDirectory = subpath === ROOT_SUBPATH ? "" : moduleDirectoryNamedBy(subpath);
58
66
  return (
59
- !NOT_A_DIRECTORY_NAME.has(sourceOrBuildDirectory) &&
67
+ !NOT_A_DIRECTORY_NAME.has(sourceDirectory) &&
60
68
  fileName !== undefined &&
61
69
  INDEX_FILE.test(fileName) &&
62
- insideTheSourceOrBuildDirectory.slice(0, -1).join("/") === namedDirectory
70
+ insideTheSourceDirectory.slice(0, -1).join("/") === namedDirectory
63
71
  );
64
72
  };
65
73
 
@@ -72,7 +80,7 @@ export const exportPathMismatches = (path: string, manifest: typeof JSON_OBJECT.
72
80
  targetsUnderEveryCondition(field, value)
73
81
  .filter(
74
82
  ({ target }) =>
75
- CODE_FILE.test(target.replace(QUERY_OR_FRAGMENT, "")) &&
83
+ isTypeScriptSourceFile(target.replace(QUERY_OR_FRAGMENT, "")) &&
76
84
  !isIndexOfTheDirectoryTheSubpathNames(subpath, target),
77
85
  )
78
86
  .map(
@@ -81,3 +89,27 @@ export const exportPathMismatches = (path: string, manifest: typeof JSON_OBJECT.
81
89
  ),
82
90
  );
83
91
  };
92
+
93
+ const isCodeOtherThanTypeScriptSource = (target: string) => {
94
+ const file = target.replace(QUERY_OR_FRAGMENT, "");
95
+ const isExtensionlessFile =
96
+ !FILE_EXTENSION.test(file) && !file.includes(PACKAGE_PATTERN_WILDCARD);
97
+ return !isTypeScriptSourceFile(file) && (CODE_FILE.test(file) || isExtensionlessFile);
98
+ };
99
+
100
+ export const packageEntriesNotTypeScript = (path: string, manifest: typeof JSON_OBJECT.Type) => {
101
+ const exports = manifest["exports"];
102
+ return [
103
+ ...ENTRY_FIELDS.flatMap((field) => {
104
+ const target = manifest[field];
105
+ return typeof target === "string" ? [{ field, target }] : [];
106
+ }),
107
+ ...(exports === undefined
108
+ ? []
109
+ : subpathsWithTheirFields(exports).flatMap(({ field, value }) =>
110
+ targetsUnderEveryCondition(field, value),
111
+ )),
112
+ ]
113
+ .filter(({ target }) => isCodeOtherThanTypeScriptSource(target))
114
+ .map(({ field, target }) => new PackageEntryNotTypeScript({ location: path, field, target }));
115
+ };
@@ -47,7 +47,7 @@ import {
47
47
  directoryOf,
48
48
  directoriesNestedInLayoutDirectoriesOf,
49
49
  } from "../../../shared/classify-files-by-role.ts";
50
- import { lineNumberAt } from "../../../shared/count-the-line-of-an-offset.ts";
50
+ import { lineNumbersIn } from "../../../shared/count-the-line-of-an-offset.ts";
51
51
  import { PACKAGE_MANIFEST_FILE } from "../../../shared/find-named-package-manifests.ts";
52
52
  import { isInsideAnyDirectory, listedPackageFiles } from "../../../shared/list-package-files.ts";
53
53
  import { loadedLintConfigIn } from "../../../shared/load-the-lint-config.ts";
@@ -96,7 +96,10 @@ import {
96
96
  UngrantedDirectory,
97
97
  UnlistedPatchGranted,
98
98
  } from "./file-layout-errors.ts";
99
- import { exportPathMismatches } from "./find-export-path-mismatches.ts";
99
+ import {
100
+ exportPathMismatches,
101
+ packageEntriesNotTypeScript,
102
+ } from "./find-export-path-mismatches.ts";
100
103
  import {
101
104
  directoriesOutsideModuleLayoutAmong,
102
105
  isLibraryDirectoryOfAModule,
@@ -326,11 +329,12 @@ export const sourceViolations = (
326
329
  }
327
330
  const isTopLevelScriptWithMain = isTopLevelScript(path) && !isTopLevelScriptWithoutMain;
328
331
  if (isTopLevelScriptWithMain) {
332
+ const lineAt = lineNumbersIn(text);
329
333
  violations.push(
330
334
  ...statementsOtherThanImportsAndMain(parsed, imports).map(
331
335
  (statement) =>
332
336
  new TopLevelScriptHoldsOtherStatement({
333
- location: `${path}:${lineNumberAt(text, statement.start)}`,
337
+ location: `${path}:${lineAt(statement.start)}`,
334
338
  }),
335
339
  ),
336
340
  );
@@ -577,6 +581,7 @@ export const manifestViolations = (
577
581
  return [
578
582
  ...scriptsViolations,
579
583
  ...(yield* dependenciesOutsideRepository(path, manifest.success, repository)),
584
+ ...packageEntriesNotTypeScript(path, manifest.success),
580
585
  ...exportPathMismatches(path, manifest.success),
581
586
  ];
582
587
  });
@@ -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 { fileTypeViolationsOfEachPackage } from "./internal/find-file-type-violations.ts";
4
6
 
5
- export const fileTypes = Task.make("file-types", fileTypeViolationsOfEachPackage);
7
+ export const fileTypes = Task.make(
8
+ "file-types",
9
+ fileTypeViolationsOfEachPackage.pipe(Effect.provide(ProjectQueryCachesLive)),
10
+ );
@@ -5,6 +5,7 @@ import { inEachPackage, packageDirectoriesIn } from "../../../shared/check-each-
5
5
  import { ownedFilesAmong } from "../../../shared/list-owned-files.ts";
6
6
  import { listedPackageFiles } from "../../../shared/list-package-files.ts";
7
7
  import { quietViolations } from "../../../shared/print-failures-and-keep-detail-in-the-trace.ts";
8
+ import { ProjectQueryCachesLive } from "../../../shared/provide-project-query-caches.ts";
8
9
  import {
9
10
  FORMATTED_PACKAGE_DIRECTORY,
10
11
  unformattedFilesAmong,
@@ -35,7 +36,7 @@ const formatterFiles = Task.make(
35
36
  .flatMap(({ directory, files }) => files.map((file) => path.join(directory, file)))
36
37
  .toSorted(),
37
38
  };
38
- }).pipe(quietViolations("formatter-files")),
39
+ }).pipe(quietViolations("formatter-files"), Effect.provide(ProjectQueryCachesLive)),
39
40
  );
40
41
 
41
42
  const formatInputs = Task.make(
@@ -57,7 +58,7 @@ const unformattedFiles = Task.make(
57
58
  checkedFormatConfigIn(packageDirectory).pipe(quietViolations("bun-fmt")),
58
59
  ),
59
60
  Effect.flatMap(formatterFiles, ({ packageFiles }) => unformattedFilesAmong(packageFiles)),
60
- ),
61
+ ).pipe(Effect.provide(ProjectQueryCachesLive)),
61
62
  );
62
63
 
63
64
  export const formatting = Task.make(
@@ -14,7 +14,7 @@ import {
14
14
  LAYOUT_DIRECTORY_NAMES,
15
15
  SHARED_DIRECTORY_NAME,
16
16
  } from "../../../../../shared/match-file-names-and-path-prefixes.ts";
17
- import { lineNumberAt } from "../../../shared/count-the-line-of-an-offset.ts";
17
+ import { lineNumbersIn } from "../../../shared/count-the-line-of-an-offset.ts";
18
18
  import { moduleResolverFor } from "../../../shared/create-the-module-resolver.ts";
19
19
  import {
20
20
  directoriesAFailedResolutionReads,
@@ -32,7 +32,7 @@ const OWN_LAYOUT_DIRECTORIES = `${INTERNAL_DIRECTORY_NAME}/ and ${SHARED_DIRECTO
32
32
  const RE_EXPORTABLE_EXTENSIONS = ".ts or .tsx";
33
33
  const RE_EXPORTABLE_FILE = /^.+\.tsx?$/u;
34
34
  const INDEX_FILE = /^index(?:\.d)?\.tsx?$/u;
35
- const NAMESPACE_INDEX = /^\.\/lib\/[^/.][^/]*\/index\.ts$/u;
35
+ const NAMESPACE_INDEX = /^\.\/lib\/[^/.][^/]*\/index\.tsx?$/u;
36
36
  const INSTALLED_PACKAGES_DIRECTORY = "node_modules";
37
37
  const FILE_SYSTEM_ROOT = "/";
38
38
  const GIT_DIRECTORY_NAME = ".git";
@@ -77,9 +77,7 @@ const repositoryRootHolding = Effect.fn("repositoryRootHolding")(function* (dire
77
77
  const fileSystem = yield* FileSystem.FileSystem;
78
78
  for (const manifestFile of enclosingPackageManifestsOf(directory, FILE_SYSTEM_ROOT)) {
79
79
  const enclosing = directoryHolding(manifestFile);
80
- const holdsGit = yield* fileSystem
81
- .exists(`${enclosing}/${GIT_DIRECTORY_NAME}`)
82
- .pipe(Effect.catchTag("PlatformError", () => Effect.succeed(false)));
80
+ const holdsGit = yield* fileSystem.exists(`${enclosing}/${GIT_DIRECTORY_NAME}`);
83
81
  if (holdsGit) {
84
82
  return enclosing;
85
83
  }
@@ -121,11 +119,15 @@ const badManifestOf = (directory: string, failure: PackageManifestUnreadable) =>
121
119
  }) as const;
122
120
 
123
121
  const resolvedRequest = (importingFile: string, request: string) =>
124
- Effect.tryPromise({
125
- try: () => moduleResolverFor([]).resolveFileAsync(importingFile, request),
126
- catch: (cause) =>
127
- new ModuleRequestUnresolvable({ request, importingFile, reason: String(cause) }),
128
- });
122
+ moduleResolverFor([]).pipe(
123
+ Effect.flatMap((resolver) =>
124
+ Effect.tryPromise({
125
+ try: () => resolver.resolveFileAsync(importingFile, request),
126
+ catch: (cause) =>
127
+ new ModuleRequestUnresolvable({ request, importingFile, reason: String(cause) }),
128
+ }),
129
+ ),
130
+ );
129
131
 
130
132
  const unresolvedFactOf = Effect.fn("unresolvedFactOf")(function* (
131
133
  index: Effect.Success<ReturnType<typeof realIndexOf>>,
@@ -224,16 +226,18 @@ const exportsOwnInternalNames = Effect.fn("exportsOwnInternalNames")(function* (
224
226
  return false;
225
227
  }
226
228
  const fact = yield* resolvedFactOf(index, source.value);
229
+ const resolved = (yield* resolvedRequest(index.file, source.value)).path;
230
+ const ownInternalDirectory = `${index.directory}/${INTERNAL_DIRECTORY_NAME}`;
231
+ const isInOwnInternalDirectory =
232
+ resolved !== undefined &&
233
+ directoryHolding(yield* fileSystem.realPath(resolved)) === ownInternalDirectory;
227
234
  const exportsUnrenamedNames =
228
235
  statement.specifiers.length > 0 &&
229
236
  statement.specifiers.every(
230
237
  (specifier) => exportedName(specifier.local) === exportedName(specifier.exported),
231
238
  );
232
239
  const isOwnInternalReExport =
233
- fact !== undefined &&
234
- "allowed" in fact &&
235
- exportsUnrenamedNames &&
236
- source.value.startsWith(`./${INTERNAL_DIRECTORY_NAME}/`);
240
+ fact !== undefined && "allowed" in fact && exportsUnrenamedNames && isInOwnInternalDirectory;
237
241
  if (!isOwnInternalReExport) {
238
242
  return false;
239
243
  }
@@ -266,7 +270,7 @@ export const indexReExportJudgmentsOf = Effect.fn("indexReExportJudgmentsOf")(fu
266
270
  indexFile: string,
267
271
  text: string,
268
272
  ) {
269
- moduleResolverFor([]).clearCache();
273
+ (yield* moduleResolverFor([])).clearCache();
270
274
  const { program } = parseSync(indexFile, text);
271
275
  const judgments: { readonly start: number; readonly judgment: string }[] = [];
272
276
  const exportsFromAModule = program.body.some(
@@ -280,13 +284,14 @@ export const indexReExportJudgmentsOf = Effect.fn("indexReExportJudgmentsOf")(fu
280
284
  const index = yield* realIndexOf(indexFile);
281
285
  for (const statement of program.body) {
282
286
  if (statement.type === "ExportAllDeclaration") {
283
- const source = statement.source.value;
284
- const isNamespaceOfAChildModule =
285
- statement.exported === null || (yield* exportsChildModuleNamespace(index, source));
286
- if (!isNamespaceOfAChildModule) {
287
+ const namespace = statement.exported;
288
+ const namespaceSource = statement.source.value;
289
+ const isChildModuleNamespace =
290
+ namespace === null || (yield* exportsChildModuleNamespace(index, namespaceSource));
291
+ if (!isChildModuleNamespace) {
287
292
  judgments.push({
288
293
  start: statement.start,
289
- judgment: `export * from ${source} re-exports another module`,
294
+ judgment: `export * as ${text.slice(namespace.start, namespace.end)} from ${namespaceSource} re-exports another module`,
290
295
  });
291
296
  }
292
297
  continue;
@@ -337,10 +342,11 @@ export const findIndexReExportViolations = (projectFile: string) =>
337
342
  path.join(packageDirectory, displayName),
338
343
  text,
339
344
  );
345
+ const lineAt = lineNumbersIn(text);
340
346
  return judgments.map(
341
347
  ({ start, judgment }) =>
342
348
  new IndexReExportRefused({
343
- location: `${displayName}:${lineNumberAt(text, start)}`,
349
+ location: `${displayName}:${lineAt(start)}`,
344
350
  judgment,
345
351
  }),
346
352
  );
@@ -4,6 +4,7 @@ import { Effect } from "effect";
4
4
  import { inEachPackage } from "../../shared/check-each-nested-package.ts";
5
5
  import { lintConfigFile } from "../../shared/declare-lint-config-task.ts";
6
6
  import { typeScriptConfig } from "../../shared/declare-typescript-config-task.ts";
7
+ import { ProjectQueryCachesLive } from "../../shared/provide-project-query-caches.ts";
7
8
  import { checkLintRulesWithOxlintIn } from "./internal/check-lint-rules-with-oxlint.ts";
8
9
 
9
10
  export const oxlint = Task.make(
@@ -11,5 +12,5 @@ export const oxlint = Task.make(
11
12
  Effect.andThen(
12
13
  Task.all([typeScriptConfig, lintConfigFile]),
13
14
  inEachPackage("oxlint", ".", checkLintRulesWithOxlintIn),
14
- ),
15
+ ).pipe(Effect.provide(ProjectQueryCachesLive)),
15
16
  );
@@ -88,7 +88,7 @@ const checkLintRulesWithOxlintOn = (directory: string, files: readonly string[])
88
88
  ...files.filter((file) => file.includes("\\")).map((file) => [file]),
89
89
  ],
90
90
  exitsOfOxlintOn(directory),
91
- ).pipe(quietViolations(OXLINT_TASK));
91
+ ).pipe(Effect.withSpan("lint-rules"), quietViolations(OXLINT_TASK));
92
92
  const flatExits = exits.flat();
93
93
  if (Arrays.isReadonlyArrayNonEmpty(flatExits)) {
94
94
  return yield* Effect.fail(mergedExit(flatExits)).pipe(
@@ -108,14 +108,17 @@ const reportedErrorsOf = <Requirements>(check: Effect.Effect<void, ReportedError
108
108
  export const checkLintRulesWithOxlintIn = (directory: string) =>
109
109
  Effect.gen(function* () {
110
110
  const files = yield* filesToLintIn(directory);
111
- const reportedErrors = yield* Effect.all([
112
- reportedErrorsOf(checkLintRulesWithOxlintOn(directory, files)),
113
- reportedErrorsOf(
114
- checkUnsafeEnumAssignmentsIn(directory, files).pipe(
115
- Effect.withSpan("unsafe-enum-assignments"),
111
+ const reportedErrors = yield* Effect.all(
112
+ [
113
+ reportedErrorsOf(checkLintRulesWithOxlintOn(directory, files)),
114
+ reportedErrorsOf(
115
+ checkUnsafeEnumAssignmentsIn(directory, files).pipe(
116
+ Effect.withSpan("unsafe-enum-assignments"),
117
+ ),
116
118
  ),
117
- ),
118
- ]);
119
+ ],
120
+ { concurrency: "unbounded" },
121
+ );
119
122
  const allReportedErrors = reportedErrors.flat();
120
123
  if (Arrays.isReadonlyArrayNonEmpty(allReportedErrors)) {
121
124
  return yield* new ReportedErrors({ reportedErrors: allReportedErrors });
@@ -1,4 +1,4 @@
1
- import { Effect, Schema } from "effect";
1
+ import { Effect, Order, Schema } from "effect";
2
2
 
3
3
  import { encodeJson } from "../../../shared/encode-compact-json.ts";
4
4
  import { decodedReport } from "../../../shared/run-tools-and-decode-their-reports.ts";
@@ -27,8 +27,23 @@ const OXLINT_REPORT = Schema.fromJsonString(
27
27
  }),
28
28
  );
29
29
 
30
+ const labelOf = (reported: (typeof OXLINT_REPORT.Type)["diagnostics"][number]) =>
31
+ reported.labels.find(({ span }) => span.line !== null)?.span;
32
+
33
+ const DIAGNOSTIC_ORDER = Order.mapInput(
34
+ Order.Tuple([Order.String, Order.Number, Order.Number, Order.String, Order.String]),
35
+ (reported: (typeof OXLINT_REPORT.Type)["diagnostics"][number]) =>
36
+ [
37
+ reported.filename,
38
+ labelOf(reported)?.line ?? 0,
39
+ labelOf(reported)?.column ?? 0,
40
+ reported.code ?? "",
41
+ reported.message,
42
+ ] as const,
43
+ );
44
+
30
45
  const oxlintError = (reported: (typeof OXLINT_REPORT.Type)["diagnostics"][number]) => {
31
- const label = reported.labels.find(({ span }) => span.line !== null)?.span;
46
+ const label = labelOf(reported);
32
47
  const location =
33
48
  label === undefined
34
49
  ? reported.filename
@@ -47,6 +62,7 @@ export const oxlintReport = (program: string, ...standardOutputs: readonly strin
47
62
  return {
48
63
  violations: diagnostics
49
64
  .filter((reported) => reported.severity !== OXLINT_WARNING)
65
+ .toSorted(DIAGNOSTIC_ORDER)
50
66
  .map((reported) => oxlintError(reported)),
51
67
  notes:
52
68
  warnings.length === 0
@@ -36,6 +36,16 @@ export class TestOnlyExport extends Schema.TaggedError<TestOnlyExport>()("TestOn
36
36
  }
37
37
  }
38
38
 
39
+ export class ScriptOnlyExport extends Schema.TaggedError<ScriptOnlyExport>()("ScriptOnlyExport", {
40
+ location: Schema.String,
41
+ exportName: Schema.String,
42
+ isUsedByTests: Schema.Boolean,
43
+ }) {
44
+ public override get message() {
45
+ return `export ${this.exportName} is used only by ${this.isUsedByTests ? "tests and scripts" : "scripts"}`;
46
+ }
47
+ }
48
+
39
49
  const UNCOUNTED_USERS = "outside tests and unreached code";
40
50
 
41
51
  export class FileBesideSubdirectories extends Schema.TaggedError<FileBesideSubdirectories>()(
@@ -98,7 +108,7 @@ export class PackageEntryWithoutSource extends Schema.TaggedError<PackageEntryWi
98
108
  },
99
109
  ) {
100
110
  public override get message() {
101
- return `lists the entry ${this.entry}, which maps to no source file through any tsconfig outDir and rootDir`;
111
+ return `lists the entry ${this.entry}, which names no file the TypeScript project compiles`;
102
112
  }
103
113
  }
104
114
 
@@ -118,6 +128,7 @@ export class ExportPlacementViolations extends Schema.TaggedError<ExportPlacemen
118
128
  Schema.Union([
119
129
  UnusedExport,
120
130
  TestOnlyExport,
131
+ ScriptOnlyExport,
121
132
  FileBesideSubdirectories,
122
133
  FileOutsideModuleLayout,
123
134
  SharedFileWithOneUser,
@@ -11,15 +11,23 @@ import type {
11
11
  Statement,
12
12
  } from "oxc-parser";
13
13
 
14
- import { isWithin } from "../../../../../shared/match-file-names-and-path-prefixes.ts";
15
- import { SCRIPTS_DIRECTORY } from "../../../../../shared/test-home-directories.ts";
16
14
  import {
15
+ fileNameOf,
16
+ isEntryFileName,
17
+ isWithin,
18
+ } from "../../../../../shared/match-file-names-and-path-prefixes.ts";
19
+ import {
20
+ SCRIPTS_DIRECTORY,
21
+ SOURCE_DIRECTORY,
22
+ } from "../../../../../shared/test-home-directories.ts";
23
+ import {
24
+ directoryOf,
17
25
  isTopLevelScript,
18
26
  isDeclarationFile,
19
27
  isTestEntryFile,
20
28
  isUnderTestDirectory,
21
29
  } from "../../../shared/classify-files-by-role.ts";
22
- import { lineNumberAt } from "../../../shared/count-the-line-of-an-offset.ts";
30
+ import { lineNumbersIn } from "../../../shared/count-the-line-of-an-offset.ts";
23
31
  import { ownedFilesAmong } from "../../../shared/list-owned-files.ts";
24
32
  import { projectSymbolsIn } from "../../../shared/query-the-typescript-project.ts";
25
33
  import type { openTypeScriptProjects } from "../../../shared/query-the-typescript-project.ts";
@@ -27,6 +35,7 @@ import { absolutePathOf } from "../../../shared/resolve-absolute-paths.ts";
27
35
  import {
28
36
  ExportPlacementViolations,
29
37
  PackageEntryWithoutSource,
38
+ ScriptOnlyExport,
30
39
  TestNotRun,
31
40
  TestOnlyExport,
32
41
  UnusedExport,
@@ -75,8 +84,18 @@ const parsedFile = (
75
84
  ) =>
76
85
  Effect.gen(function* () {
77
86
  const body = parsed.program.body;
78
- const statementAt = (offset: number) =>
79
- body.findIndex((statement) => statement.start <= offset && offset < statement.end);
87
+ const statementAt = (offset: number, low = 0, high = body.length): number => {
88
+ if (low >= high) {
89
+ return -1;
90
+ }
91
+ const middle = (low + high) >>> 1;
92
+ if (offset < (body[middle]?.start ?? offset)) {
93
+ return statementAt(offset, low, middle);
94
+ }
95
+ return offset < (body[middle]?.end ?? offset)
96
+ ? middle
97
+ : statementAt(offset, middle + 1, high);
98
+ };
80
99
  const statementOfLocal = new Map(
81
100
  [...body.entries()].flatMap(([index, statement]) =>
82
101
  declaredNamesOf(statement).map((name) => [name, index] as const),
@@ -88,6 +107,7 @@ const parsedFile = (
88
107
  entry.localName.name === null
89
108
  ? statementAt(entry.start)
90
109
  : statementOfLocal.get(entry.localName.name);
110
+ const lineAt = lineNumbersIn(text);
91
111
  const exports = new Map<
92
112
  string,
93
113
  { statement: ReturnType<typeof exportedStatement>; line: number }
@@ -103,7 +123,7 @@ const parsedFile = (
103
123
  continue;
104
124
  }
105
125
  const statement = exportedStatement(entry);
106
- exports.set(exportedName, { statement, line: lineNumberAt(text, entry.start) });
126
+ exports.set(exportedName, { statement, line: lineAt(entry.start) });
107
127
  if (localName !== null) {
108
128
  localNameOfExport.set(exportedName, localName);
109
129
  }
@@ -275,12 +295,13 @@ const parsedFile = (
275
295
  }
276
296
  } else {
277
297
  const exportedLocals = new Set(localNameOfExport.values());
298
+ const candidatesNamed = Map.groupBy(candidates, (identifier) => identifier.name);
278
299
  const declarationOf = new Map(
279
300
  [...exportedLocals].flatMap((name) => {
280
301
  const declaring = statementOfLocal.get(name);
281
- const declared = candidates.find(
282
- (identifier) => identifier.name === name && statementAt(identifier.start) === declaring,
283
- );
302
+ const declared = candidatesNamed
303
+ .get(name)
304
+ ?.find((identifier) => statementAt(identifier.start) === declaring);
284
305
  return declared === undefined ? [] : [[name, declared.start] as const];
285
306
  }),
286
307
  );
@@ -317,6 +338,17 @@ const parsedFile = (
317
338
  };
318
339
  });
319
340
 
341
+ const violationOfAnExportUsedOnlyBy = (
342
+ users: readonly string[],
343
+ exported: { readonly location: string; readonly exportName: string },
344
+ ) =>
345
+ users.some((user) => isWithin(user, SCRIPTS_DIRECTORY))
346
+ ? new ScriptOnlyExport({
347
+ ...exported,
348
+ isUsedByTests: users.some((user) => isUnderTestDirectory(user)),
349
+ })
350
+ : new TestOnlyExport(exported);
351
+
320
352
  export const findExportPlacementViolations = <Failure, Requirements>(
321
353
  projectFile: string,
322
354
  openedProjects: Effect.Effect<
@@ -363,6 +395,18 @@ export const findExportPlacementViolations = <Failure, Requirements>(
363
395
  (use) => use.kind !== "type",
364
396
  );
365
397
 
398
+ const builtByScripts = new Set(
399
+ [...files].flatMap(([file, parsed]) =>
400
+ isWithin(file, SCRIPTS_DIRECTORY)
401
+ ? parsed.uses.filter((use) => use.kind === "build").map((use) => use.file)
402
+ : [],
403
+ ),
404
+ );
405
+ const isServedOnlyToScripts = (file: string) =>
406
+ isWithin(file, SOURCE_DIRECTORY) &&
407
+ !builtByScripts.has(file) &&
408
+ !(directoryOf(file) === SOURCE_DIRECTORY && isEntryFileName(fileNameOf(file)));
409
+
366
410
  const users = new Map<string, Map<string, Set<string>>>();
367
411
  const usersOf = (file: string, name: string) => {
368
412
  const byName = users.get(file) ?? new Map<string, Set<string>>();
@@ -371,8 +415,8 @@ export const findExportPlacementViolations = <Failure, Requirements>(
371
415
  byName.set(name, found);
372
416
  return found;
373
417
  };
374
- const exportedNamesOf = (file: string): ReadonlySet<string> =>
375
- new Set(files.get(file)?.exports.keys());
418
+ const isExportedFrom = (file: string, name: string) =>
419
+ files.get(file)?.exports.has(name) ?? false;
376
420
  const everyExportUsers = new Map<string, Set<string>>();
377
421
  const everyExportUsersOf = (file: string) => {
378
422
  const found = everyExportUsers.get(file) ?? new Set<string>();
@@ -398,7 +442,7 @@ export const findExportPlacementViolations = <Failure, Requirements>(
398
442
  }
399
443
  const allUsersOf = (file: string, name: string): ReadonlySet<string> => {
400
444
  const named = users.get(file)?.get(name);
401
- const everyUser = exportedNamesOf(file).has(name) ? everyExportUsers.get(file) : undefined;
445
+ const everyUser = isExportedFrom(file, name) ? everyExportUsers.get(file) : undefined;
402
446
  if (everyUser === undefined) {
403
447
  return named ?? new Set();
404
448
  }
@@ -407,15 +451,21 @@ export const findExportPlacementViolations = <Failure, Requirements>(
407
451
 
408
452
  for (const [file, parsed] of files) {
409
453
  const inherits: { readonly from: string; readonly to: string }[] = [];
454
+ const statementsReferencing = new Map<string, number[]>();
455
+ for (const [index, references] of parsed.referencesByStatement.entries()) {
456
+ for (const reference of references) {
457
+ const statements = statementsReferencing.get(reference) ?? [];
458
+ statements.push(index);
459
+ statementsReferencing.set(reference, statements);
460
+ }
461
+ }
410
462
  for (const [name, exported] of parsed.exports) {
411
463
  const localName = parsed.localNameOfExport.get(name);
412
464
  if (localName === undefined) {
413
465
  continue;
414
466
  }
415
- for (const [index, references] of parsed.referencesByStatement.entries()) {
416
- const isReferencedFromAnotherStatement =
417
- exported.statement !== index && references.has(localName);
418
- if (!isReferencedFromAnotherStatement) {
467
+ for (const index of statementsReferencing.get(localName) ?? []) {
468
+ if (exported.statement === index) {
419
469
  continue;
420
470
  }
421
471
  const exportingNames = (parsed.exportsOfStatement.get(index) ?? []).filter(
@@ -445,7 +495,7 @@ export const findExportPlacementViolations = <Failure, Requirements>(
445
495
  inheritUsersUntilStable();
446
496
  }
447
497
 
448
- const exportViolations: (TestOnlyExport | UnusedExport)[] = [];
498
+ const exportViolations: (ScriptOnlyExport | TestOnlyExport | UnusedExport)[] = [];
449
499
  for (const [file, parsed] of files) {
450
500
  const isExemptFromExportChecks =
451
501
  !owned.has(file) ||
@@ -464,11 +514,15 @@ export const findExportPlacementViolations = <Failure, Requirements>(
464
514
  .toSorted();
465
515
  const elsewhere = everyUser.filter((user) => user !== file);
466
516
  const usedInOwnFile = everyUser.includes(file);
467
- const isUnusedOrUsedOnlyByTests =
468
- elsewhere.every((user) => isUnderTestDirectory(user)) &&
517
+ const isUnusedOrUsedOnlyByTestsAndScripts =
518
+ elsewhere.every(
519
+ (user) =>
520
+ isUnderTestDirectory(user) ||
521
+ (isWithin(user, SCRIPTS_DIRECTORY) && isServedOnlyToScripts(file)),
522
+ ) &&
469
523
  !(usedInOwnFile && elsewhere.length > 0) &&
470
524
  (elsewhere.length === 0 || !isWithin(file, SCRIPTS_DIRECTORY));
471
- if (isUnusedOrUsedOnlyByTests) {
525
+ if (isUnusedOrUsedOnlyByTestsAndScripts) {
472
526
  exportViolations.push(
473
527
  elsewhere.length === 0
474
528
  ? new UnusedExport({
@@ -476,7 +530,7 @@ export const findExportPlacementViolations = <Failure, Requirements>(
476
530
  exportName: name,
477
531
  ...(unreachableUser === undefined ? {} : { unreachableUser }),
478
532
  })
479
- : new TestOnlyExport({ location, exportName: name }),
533
+ : violationOfAnExportUsedOnlyBy(elsewhere, { location, exportName: name }),
480
534
  );
481
535
  }
482
536
  }