@sshkeda/check 0.0.0-stage → 1.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 (167) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +156 -2
  3. package/docs/how-to-make-check-pass.md +71 -0
  4. package/package.json +51 -4
  5. package/src/index.ts +8 -0
  6. package/src/internal/ban-abbreviated-words-in-declared-names.ts +165 -0
  7. package/src/internal/ban-checked-members-outside-calls.ts +151 -0
  8. package/src/internal/ban-comments.ts +23 -0
  9. package/src/internal/ban-comparing-or-switching-on-tag.ts +114 -0
  10. package/src/internal/ban-deadlines-inside-tests.ts +41 -0
  11. package/src/internal/ban-declared-values.ts +70 -0
  12. package/src/internal/ban-dropped-failures-detached-fibers-sleeps-and-untraced-functions.ts +67 -0
  13. package/src/internal/ban-failures-collected-as-results.ts +57 -0
  14. package/src/internal/ban-fallbacks-of-named-recoveries.ts +118 -0
  15. package/src/internal/ban-function-overloads.ts +107 -0
  16. package/src/internal/ban-global-error-in-failure-types.ts +146 -0
  17. package/src/internal/ban-instanceof-in-effect-recovery-callbacks.ts +63 -0
  18. package/src/internal/ban-let-and-effect-mutable-ref.ts +79 -0
  19. package/src/internal/ban-logic-in-index-files.ts +178 -0
  20. package/src/internal/ban-namespaces-used-without-a-member.ts +176 -0
  21. package/src/internal/ban-node-builtins-that-effect-replaces.ts +42 -0
  22. package/src/internal/ban-parsing-outside-data-without-a-schema.ts +299 -0
  23. package/src/internal/ban-re-exports.ts +172 -0
  24. package/src/internal/ban-reading-the-clock-and-sleeping-outside-effect.ts +239 -0
  25. package/src/internal/ban-retired-words-in-names.ts +49 -0
  26. package/src/internal/ban-scanning-directories-with-bun-glob.ts +79 -0
  27. package/src/internal/ban-shebang-lines.ts +26 -0
  28. package/src/internal/ban-timer-globals-and-the-global-object.ts +34 -0
  29. package/src/internal/ban-timer-schedules-without-deadlines.ts +240 -0
  30. package/src/internal/ban-type-and-interface-declarations.ts +48 -0
  31. package/src/internal/ban-type-predicates.ts +82 -0
  32. package/src/internal/ban-unknown-in-function-signatures.ts +143 -0
  33. package/src/internal/ban-vague-error-class-names.ts +28 -0
  34. package/src/internal/ban-vague-file-names.ts +51 -0
  35. package/src/internal/ban-what-a-file-is-not-granted.ts +512 -0
  36. package/src/internal/ban-while-do-while-and-for-loops.ts +27 -0
  37. package/src/internal/confine-service-declarations-to-granted-files.ts +116 -0
  38. package/src/internal/confine-the-stdio-service-to-terminal-output.ts +190 -0
  39. package/src/internal/define-the-lint-plugin-and-configs.ts +361 -0
  40. package/src/internal/describe-and-decode-rule-options.ts +22 -0
  41. package/src/internal/keep-assertions-in-the-test-home-and-ban-test-runners.ts +128 -0
  42. package/src/internal/keep-effect-testing-helpers-in-test-files.ts +157 -0
  43. package/src/internal/match-banned-modules-and-globals.ts +71 -0
  44. package/src/internal/match-effect-service-factories.ts +20 -0
  45. package/src/internal/require-a-named-const-for-compound-conditions.ts +44 -0
  46. package/src/internal/require-capital-snake-case-and-as-const-on-literal-constants.ts +141 -0
  47. package/src/internal/require-service-keys-to-end-with-their-class-name.ts +64 -0
  48. package/src/internal/resolve-what-an-expression-imports.ts +295 -0
  49. package/src/internal/sort-type-constituents.ts +82 -0
  50. package/src/internal/split-names-into-words.ts +12 -0
  51. package/src/internal/visit-every-declared-name.ts +264 -0
  52. package/src/lib/tasks/index.ts +1 -0
  53. package/src/lib/tasks/internal/declare-the-check-task.ts +29 -0
  54. package/src/lib/tasks/internal/declare-the-checker-queries-task.ts +41 -0
  55. package/src/lib/tasks/internal/declare-the-typed-checks-task.ts +25 -0
  56. package/src/lib/tasks/internal/run-checks-over-one-typescript-project.ts +68 -0
  57. package/src/lib/tasks/lib/check-effect-diagnostics-with-effect-tsgo/index.ts +15 -0
  58. package/src/lib/tasks/lib/check-effect-diagnostics-with-effect-tsgo/internal/check-effect-diagnostics-with-effect-tsgo.ts +211 -0
  59. package/src/lib/tasks/lib/check-effect-diagnostics-with-effect-tsgo/internal/read-effect-tsgo-json-report.ts +39 -0
  60. package/src/lib/tasks/lib/check-import-boundaries/index.ts +1 -0
  61. package/src/lib/tasks/lib/check-import-boundaries/internal/find-import-boundary-violations.ts +415 -0
  62. package/src/lib/tasks/lib/check-import-boundaries/internal/find-subpath-import-targets.ts +117 -0
  63. package/src/lib/tasks/lib/check-import-boundaries/internal/find-what-hides-an-import.ts +65 -0
  64. package/src/lib/tasks/lib/check-import-boundaries/internal/import-boundary-errors.ts +176 -0
  65. package/src/lib/tasks/lib/check-uses-by-their-declarations/index.ts +1 -0
  66. package/src/lib/tasks/lib/check-uses-by-their-declarations/internal/declared-use-errors.ts +32 -0
  67. package/src/lib/tasks/lib/check-uses-by-their-declarations/internal/find-declared-use-violations.ts +38 -0
  68. package/src/lib/tasks/lib/check-uses-by-their-declarations/internal/find-sync-calls.ts +23 -0
  69. package/src/lib/tasks/lib/check-uses-by-their-declarations/internal/find-type-only-schemas.ts +375 -0
  70. package/src/lib/tasks/lib/confine-layer-provides-to-program-starts/index.ts +1 -0
  71. package/src/lib/tasks/lib/confine-layer-provides-to-program-starts/internal/find-layer-provides-outside-program-starts.ts +648 -0
  72. package/src/lib/tasks/lib/confine-layer-provides-to-program-starts/internal/layer-provide-errors.ts +27 -0
  73. package/src/lib/tasks/lib/confine-layer-provides-to-program-starts/internal/resolve-imported-package-apis.ts +262 -0
  74. package/src/lib/tasks/lib/confine-stdio-to-granted-files/index.ts +1 -0
  75. package/src/lib/tasks/lib/confine-stdio-to-granted-files/internal/find-ungranted-stdio-uses.ts +219 -0
  76. package/src/lib/tasks/lib/confine-stdio-to-granted-files/internal/stdio-use-errors.ts +31 -0
  77. package/src/lib/tasks/lib/detect-inferrable-annotations/index.ts +1 -0
  78. package/src/lib/tasks/lib/detect-inferrable-annotations/internal/find-inferrable-annotations.ts +357 -0
  79. package/src/lib/tasks/lib/detect-inferrable-annotations/internal/inferrable-annotation-errors.ts +33 -0
  80. package/src/lib/tasks/lib/detect-repeated-service-yields/index.ts +1 -0
  81. package/src/lib/tasks/lib/detect-repeated-service-yields/internal/find-repeated-service-yields.ts +162 -0
  82. package/src/lib/tasks/lib/detect-repeated-service-yields/internal/repeated-service-yield-errors.ts +25 -0
  83. package/src/lib/tasks/lib/enforce-file-layout/index.ts +5 -0
  84. package/src/lib/tasks/lib/enforce-file-layout/internal/check-the-layout-of-each-package.ts +9 -0
  85. package/src/lib/tasks/lib/enforce-file-layout/internal/file-layout-errors.ts +417 -0
  86. package/src/lib/tasks/lib/enforce-file-layout/internal/find-export-path-mismatches.ts +83 -0
  87. package/src/lib/tasks/lib/enforce-file-layout/internal/find-file-layout-violations.ts +827 -0
  88. package/src/lib/tasks/lib/enforce-file-layout/internal/find-module-layout-violations.ts +82 -0
  89. package/src/lib/tasks/lib/enforce-file-layout/internal/resolve-task-imports.ts +178 -0
  90. package/src/lib/tasks/lib/enforce-file-types/index.ts +5 -0
  91. package/src/lib/tasks/lib/enforce-file-types/internal/file-type-errors.ts +21 -0
  92. package/src/lib/tasks/lib/enforce-file-types/internal/find-file-type-violations.ts +78 -0
  93. package/src/lib/tasks/lib/format-with-bun-fmt/index.ts +1 -0
  94. package/src/lib/tasks/lib/format-with-bun-fmt/internal/check-formatting-with-bun-fmt.ts +157 -0
  95. package/src/lib/tasks/lib/format-with-bun-fmt/internal/declare-the-formatting-task.ts +66 -0
  96. package/src/lib/tasks/lib/format-with-bun-fmt/internal/find-format-config-violations.ts +16 -0
  97. package/src/lib/tasks/lib/format-with-bun-fmt/internal/find-format-input-violations.ts +74 -0
  98. package/src/lib/tasks/lib/format-with-bun-fmt/internal/find-symbolic-links.ts +14 -0
  99. package/src/lib/tasks/lib/format-with-bun-fmt/internal/unformatted-file-errors.ts +12 -0
  100. package/src/lib/tasks/lib/judge-index-re-exports/index.ts +1 -0
  101. package/src/lib/tasks/lib/judge-index-re-exports/internal/find-index-re-export-violations.ts +353 -0
  102. package/src/lib/tasks/lib/judge-index-re-exports/internal/index-re-export-errors.ts +21 -0
  103. package/src/lib/tasks/lib/lint-with-oxlint/index.ts +15 -0
  104. package/src/lib/tasks/lib/lint-with-oxlint/internal/check-lint-rules-with-oxlint.ts +123 -0
  105. package/src/lib/tasks/lib/lint-with-oxlint/internal/check-unsafe-enum-assignments.ts +152 -0
  106. package/src/lib/tasks/lib/lint-with-oxlint/internal/find-tsgolint-executable.ts +21 -0
  107. package/src/lib/tasks/lib/lint-with-oxlint/internal/read-oxlint-json-report.ts +82 -0
  108. package/src/lib/tasks/lib/lint-with-oxlint/internal/read-tsgolint-rule-messages.ts +68 -0
  109. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/index.ts +1 -0
  110. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/export-placement-errors.ts +135 -0
  111. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/find-export-placement-violations.ts +507 -0
  112. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/find-misplaced-files.ts +116 -0
  113. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/find-subdivided-directories.ts +29 -0
  114. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/find-the-importer-graph.ts +451 -0
  115. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/list-binding-names.ts +49 -0
  116. package/src/lib/tasks/lib/refuse-disable-directives/index.ts +15 -0
  117. package/src/lib/tasks/lib/refuse-disable-directives/internal/disable-directive-errors.ts +45 -0
  118. package/src/lib/tasks/lib/refuse-disable-directives/internal/find-disable-directives.ts +66 -0
  119. package/src/lib/tasks/lib/refuse-error-mappings-that-end-streams/index.ts +1 -0
  120. package/src/lib/tasks/lib/refuse-error-mappings-that-end-streams/internal/error-mapping-errors.ts +21 -0
  121. package/src/lib/tasks/lib/refuse-error-mappings-that-end-streams/internal/find-error-mappings-to-done.ts +135 -0
  122. package/src/lib/tasks/lib/require-separate-service-layers/index.ts +1 -0
  123. package/src/lib/tasks/lib/require-separate-service-layers/internal/find-service-layer-violations.ts +170 -0
  124. package/src/lib/tasks/lib/require-separate-service-layers/internal/service-layer-errors.ts +21 -0
  125. package/src/lib/tasks/lib/require-type-checking-every-linted-file/index.ts +14 -0
  126. package/src/lib/tasks/lib/require-type-checking-every-linted-file/internal/find-linted-files-not-type-checked.ts +117 -0
  127. package/src/lib/tasks/lib/require-type-checking-every-linted-file/internal/linted-file-errors.ts +51 -0
  128. package/src/lib/tasks/lib/type-check-with-bun-check/index.ts +11 -0
  129. package/src/lib/tasks/lib/type-check-with-bun-check/internal/check-types-with-bun-check.ts +54 -0
  130. package/src/lib/tasks/lib/type-check-with-bun-check/internal/read-bun-check-output.ts +73 -0
  131. package/src/lib/tasks/lib/type-check-with-bun-check/internal/type-check-errors.ts +10 -0
  132. package/src/lib/tasks/shared/check-each-nested-package.ts +79 -0
  133. package/src/lib/tasks/shared/classify-files-by-role.ts +115 -0
  134. package/src/lib/tasks/shared/count-the-line-of-an-offset.ts +2 -0
  135. package/src/lib/tasks/shared/create-the-module-resolver.ts +38 -0
  136. package/src/lib/tasks/shared/declare-lint-config-task.ts +13 -0
  137. package/src/lib/tasks/shared/declare-typescript-config-task.ts +18 -0
  138. package/src/lib/tasks/shared/encode-compact-json.ts +5 -0
  139. package/src/lib/tasks/shared/find-installed-package-binaries.ts +62 -0
  140. package/src/lib/tasks/shared/find-module-requests.ts +482 -0
  141. package/src/lib/tasks/shared/find-named-package-manifests.ts +94 -0
  142. package/src/lib/tasks/shared/find-unmet-typescript-config-requirements.ts +60 -0
  143. package/src/lib/tasks/shared/list-ignored-files-imported-by-source.ts +79 -0
  144. package/src/lib/tasks/shared/list-linted-files.ts +28 -0
  145. package/src/lib/tasks/shared/list-owned-files.ts +13 -0
  146. package/src/lib/tasks/shared/list-package-files.ts +66 -0
  147. package/src/lib/tasks/shared/load-the-lint-config.ts +176 -0
  148. package/src/lib/tasks/shared/match-granted-patch-files.ts +88 -0
  149. package/src/lib/tasks/shared/parse-config-files-that-import-from-check.ts +310 -0
  150. package/src/lib/tasks/shared/print-failures-and-keep-detail-in-the-trace.ts +99 -0
  151. package/src/lib/tasks/shared/project-config-and-tool-errors.ts +485 -0
  152. package/src/lib/tasks/shared/query-the-typescript-project.ts +635 -0
  153. package/src/lib/tasks/shared/read-named-package-manifests.ts +53 -0
  154. package/src/lib/tasks/shared/read-package-manifest-object.ts +28 -0
  155. package/src/lib/tasks/shared/resolve-absolute-paths.ts +4 -0
  156. package/src/lib/tasks/shared/resolve-module-requests.ts +121 -0
  157. package/src/lib/tasks/shared/run-tools-and-decode-their-reports.ts +98 -0
  158. package/src/lib/tasks/shared/tool-file-locations.ts +38 -0
  159. package/src/shared/bans-each-permission-lifts.ts +454 -0
  160. package/src/shared/config-file-names.ts +3 -0
  161. package/src/shared/find-retired-words.ts +17 -0
  162. package/src/shared/format-reported-failures.ts +31 -0
  163. package/src/shared/lint-rule-messages-and-patterns.ts +104 -0
  164. package/src/shared/match-file-names-and-path-prefixes.ts +18 -0
  165. package/src/shared/permission-grant-errors.ts +42 -0
  166. package/src/shared/record-and-grant-permissions-by-path.ts +419 -0
  167. package/src/shared/test-home-directories.ts +4 -0
@@ -0,0 +1,415 @@
1
+ import { Effect, FileSystem, Path, Schema } from "effect";
2
+ import { parseSync } from "oxc-parser";
3
+
4
+ import { fileNameOf, isWithin } from "../../../../../shared/match-file-names-and-path-prefixes.ts";
5
+ import {
6
+ SCRIPTS_DIRECTORY,
7
+ SOURCE_DIRECTORY,
8
+ TEST_DIRECTORY,
9
+ } from "../../../../../shared/test-home-directories.ts";
10
+ import {
11
+ isFileSpecifier,
12
+ isScript,
13
+ directoriesNestedInLayoutDirectoriesOf,
14
+ moduleDirectoriesAmong,
15
+ packagePathOf,
16
+ repeatsSourceNeverImportsScripts,
17
+ SOURCE_NEVER_IMPORTS_SCRIPTS,
18
+ } from "../../../shared/classify-files-by-role.ts";
19
+ import { lineNumberAt } from "../../../shared/count-the-line-of-an-offset.ts";
20
+ import {
21
+ moduleRequestsIn,
22
+ moduleUrlMisusesIn,
23
+ URL_REQUESTS,
24
+ } from "../../../shared/find-module-requests.ts";
25
+ import type { MODULE_REQUEST_KINDS } from "../../../shared/find-module-requests.ts";
26
+ import { PACKAGE_MANIFEST_FILE } from "../../../shared/find-named-package-manifests.ts";
27
+ import { ignoredPackagePathsAmong } from "../../../shared/list-ignored-files-imported-by-source.ts";
28
+ import { loadedLintConfigIn } from "../../../shared/load-the-lint-config.ts";
29
+ import { PackageManifestFieldInvalid } from "../../../shared/project-config-and-tool-errors.ts";
30
+ import {
31
+ checkedSourceFiles,
32
+ includedFiles,
33
+ programFiles,
34
+ CUSTOM_CONDITIONS,
35
+ effectiveCompilerOptions,
36
+ } from "../../../shared/query-the-typescript-project.ts";
37
+ import { packageManifestObject } from "../../../shared/read-package-manifest-object.ts";
38
+ import { resolveModuleRequest } from "../../../shared/resolve-module-requests.ts";
39
+ import { packageRequestBehindSubpathImport } from "./find-subpath-import-targets.ts";
40
+ import { whatHidesTheImport } from "./find-what-hides-an-import.ts";
41
+ import type { IMPORT_BOUNDARY_VIOLATION } from "./import-boundary-errors.ts";
42
+ import {
43
+ CannotImportCrossed,
44
+ DevDependencyImported,
45
+ ImportBoundariesCrossed,
46
+ ImportOutsidePackage,
47
+ ModuleInternalsImported,
48
+ PlainDirectoryImported,
49
+ PrivateCodeImported,
50
+ ImportCaseMismatch,
51
+ ImportOfMissingIgnoredFile,
52
+ ImportResolvesToNoFile,
53
+ ModulePathFromDirectory,
54
+ ModuleUrlNotInline,
55
+ ModuleUrlPassedToFunction,
56
+ TestImported,
57
+ } from "./import-boundary-errors.ts";
58
+
59
+ const NODE_MODULES_DIRECTORY = "node_modules";
60
+ const REQUESTS_BUN_CHECK_RESOLVES = new Set<(typeof MODULE_REQUEST_KINDS)[number]>([
61
+ "static",
62
+ "type",
63
+ "dynamic",
64
+ ]);
65
+
66
+ const BARE_PACKAGE_NAME = /^(?:@[^/]+\/)?[^/.][^/]*/u;
67
+
68
+ const importsPackageEntry = (
69
+ specifier: string,
70
+ resolved: NonNullable<Effect.Success<ReturnType<typeof resolveModuleRequest>>>,
71
+ ) =>
72
+ !isFileSpecifier(specifier) &&
73
+ resolved.packageName !== null &&
74
+ BARE_PACKAGE_NAME.exec(specifier)?.[0] === resolved.packageName &&
75
+ (resolved.packageHasExports || specifier === resolved.packageName);
76
+
77
+ const DEPENDENCY_LIST = Schema.optionalKey(Schema.Record(Schema.String, Schema.Json));
78
+ const DEPENDENCY_LISTS = Schema.Struct({
79
+ dependencies: DEPENDENCY_LIST,
80
+ devDependencies: DEPENDENCY_LIST,
81
+ peerDependencies: DEPENDENCY_LIST,
82
+ optionalDependencies: DEPENDENCY_LIST,
83
+ });
84
+
85
+ const dependencyNamesIn = (packageDirectory: string) =>
86
+ Effect.gen(function* () {
87
+ const fileSystem = yield* FileSystem.FileSystem;
88
+ const path = yield* Path.Path;
89
+ const manifestFile = path.join(packageDirectory, PACKAGE_MANIFEST_FILE);
90
+ const manifest = yield* Effect.fromResult(
91
+ packageManifestObject(manifestFile, yield* fileSystem.readFileString(manifestFile)),
92
+ );
93
+ const lists = yield* Schema.decodeEffect(DEPENDENCY_LISTS)(manifest).pipe(
94
+ Effect.mapError(
95
+ (error) => new PackageManifestFieldInvalid({ path: manifestFile, reason: error.message }),
96
+ ),
97
+ );
98
+ const installedWithThePackage = new Set(
99
+ [lists.dependencies, lists.peerDependencies, lists.optionalDependencies].flatMap((list) =>
100
+ Object.keys(list ?? {}),
101
+ ),
102
+ );
103
+ const development = Object.keys(lists.devDependencies ?? {});
104
+ return {
105
+ declared: new Set([...installedWithThePackage, ...development]),
106
+ devOnly: new Set(development.filter((name) => !installedWithThePackage.has(name))),
107
+ };
108
+ });
109
+
110
+ const SCRIPT_EXTENSION = /\.[cm]?[jt]sx?$/u;
111
+ const withoutScriptExtension = (file: string) => file.replace(SCRIPT_EXTENSION, "");
112
+
113
+ const visibilityViolationOf = (
114
+ importerPath: string,
115
+ importedPath: string,
116
+ moduleDirectories: ReadonlySet<string>,
117
+ location: string,
118
+ otherPackageDirectory: string | undefined,
119
+ ) => {
120
+ const hidden = whatHidesTheImport(
121
+ importerPath,
122
+ importedPath,
123
+ moduleDirectories,
124
+ otherPackageDirectory,
125
+ );
126
+ if (hidden === undefined) {
127
+ return;
128
+ }
129
+ const isHiddenByAModuleOrPackage = hidden.hiddenBy === "module" || hidden.hiddenBy === "package";
130
+ if (isHiddenByAModuleOrPackage) {
131
+ return new ModuleInternalsImported({
132
+ location,
133
+ importedPath,
134
+ module: hidden.directory,
135
+ kind: hidden.hiddenBy,
136
+ });
137
+ }
138
+ if (hidden.hiddenBy === "internal") {
139
+ return new PrivateCodeImported({
140
+ location,
141
+ importedPath,
142
+ directory: hidden.directory,
143
+ module: hidden.parent,
144
+ });
145
+ }
146
+ const isReportedByTheLayoutCheck = directoriesNestedInLayoutDirectoriesOf(importedPath).includes(
147
+ hidden.directory,
148
+ );
149
+ if (isReportedByTheLayoutCheck) {
150
+ return;
151
+ }
152
+ return new PlainDirectoryImported({
153
+ location,
154
+ importedPath,
155
+ directory: hidden.directory,
156
+ parent: hidden.parent,
157
+ });
158
+ };
159
+
160
+ export const findImportBoundaryViolations = (projectFile: string) =>
161
+ Effect.gen(function* () {
162
+ const fileSystem = yield* FileSystem.FileSystem;
163
+ const path = yield* Path.Path;
164
+ const grants = yield* loadedLintConfigIn(path.dirname(projectFile));
165
+ const boundaries = [
166
+ SOURCE_NEVER_IMPORTS_SCRIPTS,
167
+ ...grants
168
+ .map((grant) => ({
169
+ path: grant.path,
170
+ cannotImport: grant.cannotImport.filter(
171
+ (target) => !repeatsSourceNeverImportsScripts(grant.path, target),
172
+ ),
173
+ }))
174
+ .filter((boundary) => boundary.cannotImport.length > 0),
175
+ ];
176
+ const packageDirectory = yield* fileSystem.realPath(path.dirname(projectFile));
177
+ const { customConditions = [] } = yield* Schema.decodeEffect(CUSTOM_CONDITIONS)(
178
+ yield* effectiveCompilerOptions(projectFile),
179
+ );
180
+ const placeOf = (fileName: string) => {
181
+ const relativePath = path.relative(packageDirectory, fileName);
182
+ const segments = relativePath.split(path.sep);
183
+ if (segments.includes(NODE_MODULES_DIRECTORY)) {
184
+ return { installed: true } as const;
185
+ }
186
+ const isOutsideThePackage = relativePath.startsWith("..") || path.isAbsolute(relativePath);
187
+ return isOutsideThePackage
188
+ ? ({ outside: true } as const)
189
+ : ({ packagePath: segments.join("/") } as const);
190
+ };
191
+ const checkedFiles = yield* checkedSourceFiles(projectFile);
192
+ const dependencies = yield* dependencyNamesIn(packageDirectory);
193
+ const typeCheckedFiles = new Set(yield* programFiles(projectFile));
194
+ const includedByTheProject = yield* includedFiles(projectFile);
195
+ const moduleDirectories = moduleDirectoriesAmong(checkedFiles);
196
+ const violations = new Map<string, typeof IMPORT_BOUNDARY_VIOLATION.Type>();
197
+ const unresolved: {
198
+ location: string;
199
+ specifier: string;
200
+ missingPath: string;
201
+ isTypeChecked: boolean;
202
+ isReportedByNoRequireImports: boolean;
203
+ }[] = [];
204
+ const add = (found: typeof IMPORT_BOUNDARY_VIOLATION.Type) =>
205
+ violations.set(`${found.location} ${found.message}`, found);
206
+ for (const displayName of checkedFiles) {
207
+ const text = yield* fileSystem.readFileString(path.join(packageDirectory, displayName));
208
+ const parsed = parseSync(displayName, text);
209
+ const bans = boundaries.flatMap((boundary) =>
210
+ isWithin(displayName, boundary.path)
211
+ ? boundary.cannotImport
212
+ .filter((target) => !isWithin(displayName, target))
213
+ .map((target) => ({
214
+ target,
215
+ grantPath: boundary.path,
216
+ isBuiltIn: boundary === SOURCE_NEVER_IMPORTS_SCRIPTS,
217
+ }))
218
+ : [],
219
+ );
220
+ if (!isWithin(displayName, TEST_DIRECTORY)) {
221
+ const { misuses, directoryPaths } = moduleUrlMisusesIn(parsed);
222
+ for (const { start, ...misuse } of misuses) {
223
+ const location = `${displayName}:${lineNumberAt(text, start)}`;
224
+ add(
225
+ "callee" in misuse
226
+ ? new ModuleUrlPassedToFunction({ location, callee: misuse.callee })
227
+ : new ModuleUrlNotInline({ location, usage: misuse.usage }),
228
+ );
229
+ }
230
+ for (const { start, property } of directoryPaths) {
231
+ add(
232
+ new ModulePathFromDirectory({
233
+ location: `${displayName}:${lineNumberAt(text, start)}`,
234
+ property,
235
+ }),
236
+ );
237
+ }
238
+ }
239
+ const importingFile = path.join(packageDirectory, displayName);
240
+ const { requests, reportedByNoRequireImports } = moduleRequestsIn(parsed);
241
+ for (const request of requests) {
242
+ if (request.kind === "build") {
243
+ continue;
244
+ }
245
+ const resolvesAPackage = request.kind === "resolve" && !isFileSpecifier(request.specifier);
246
+ const isUrlToNonScript =
247
+ URL_REQUESTS.has(request.kind) && !isScript(request.specifier) && !resolvesAPackage;
248
+ if (isUrlToNonScript) {
249
+ continue;
250
+ }
251
+ const location = `${displayName}:${lineNumberAt(text, request.start)}`;
252
+ const isTypeChecked =
253
+ REQUESTS_BUN_CHECK_RESOLVES.has(request.kind) && typeCheckedFiles.has(displayName);
254
+ const specifierText = request.specifier;
255
+ const resolved = yield* resolveModuleRequest({
256
+ request: specifierText,
257
+ importingFile,
258
+ customConditions,
259
+ projectDirectory: packageDirectory,
260
+ });
261
+ if (resolved === undefined) {
262
+ if (isFileSpecifier(specifierText)) {
263
+ unresolved.push({
264
+ location,
265
+ specifier: specifierText,
266
+ missingPath: packagePathOf(
267
+ path,
268
+ packageDirectory,
269
+ path.resolve(path.dirname(importingFile), specifierText),
270
+ ),
271
+ isTypeChecked,
272
+ isReportedByNoRequireImports: reportedByNoRequireImports.has(request.start),
273
+ });
274
+ }
275
+ continue;
276
+ }
277
+ const written = withoutScriptExtension(
278
+ path.resolve(path.dirname(importingFile), specifierText),
279
+ );
280
+ const actual = withoutScriptExtension(resolved.file);
281
+ const importedFile = path.relative(packageDirectory, resolved.file);
282
+ const differsFromWrittenPathOnlyInCase =
283
+ !(isTypeChecked && includedByTheProject.has(importedFile)) &&
284
+ isFileSpecifier(specifierText) &&
285
+ !actual.startsWith(written) &&
286
+ actual.toLowerCase().startsWith(written.toLowerCase());
287
+ if (differsFromWrittenPathOnlyInCase) {
288
+ add(
289
+ new ImportCaseMismatch({
290
+ location,
291
+ specifier: specifierText,
292
+ importedFile,
293
+ }),
294
+ );
295
+ }
296
+ const isUrlLoad = request.kind === "url" || request.kind === "launch";
297
+ const { packageName, packageRoot } = resolved;
298
+ const requestedPackage = BARE_PACKAGE_NAME.exec(specifierText)?.[0];
299
+ const isDeclaredDependency =
300
+ requestedPackage !== undefined && dependencies.declared.has(requestedPackage);
301
+ const dependencyName = isDeclaredDependency ? requestedPackage : packageName;
302
+ const isDevOnlyPackageImportedBySource =
303
+ !isUrlLoad &&
304
+ isWithin(displayName, SOURCE_DIRECTORY) &&
305
+ dependencyName !== null &&
306
+ packageRoot !== packageDirectory &&
307
+ dependencies.devOnly.has(dependencyName);
308
+ if (isDevOnlyPackageImportedBySource) {
309
+ add(
310
+ new DevDependencyImported({
311
+ location,
312
+ specifier: specifierText,
313
+ packageName: dependencyName,
314
+ }),
315
+ );
316
+ }
317
+ const place = placeOf(resolved.file);
318
+ const packageRequest = yield* packageRequestBehindSubpathImport({
319
+ request: specifierText,
320
+ importingFile,
321
+ customConditions,
322
+ projectDirectory: packageDirectory,
323
+ });
324
+ const importedThroughPackage = importsPackageEntry(
325
+ packageRequest ?? specifierText,
326
+ resolved,
327
+ );
328
+ const importsFileOutsidePackage = "outside" in place && !importedThroughPackage;
329
+ if (importsFileOutsidePackage) {
330
+ add(
331
+ new ImportOutsidePackage({
332
+ location,
333
+ specifier: specifierText,
334
+ importedFile: resolved.file,
335
+ }),
336
+ );
337
+ }
338
+ if (!("packagePath" in place)) {
339
+ continue;
340
+ }
341
+ const importedPath = place.packagePath;
342
+ const isTestImport = isWithin(importedPath, TEST_DIRECTORY);
343
+ const isTestImportedOutsideScriptsAndTests =
344
+ isTestImport &&
345
+ !isWithin(displayName, SCRIPTS_DIRECTORY) &&
346
+ !isWithin(displayName, TEST_DIRECTORY);
347
+ if (isTestImportedOutsideScriptsAndTests) {
348
+ add(new TestImported({ location, importedPath }));
349
+ }
350
+ if (isUrlLoad) {
351
+ continue;
352
+ }
353
+ const crossedBans = bans.filter((candidate) => isWithin(importedPath, candidate.target));
354
+ for (const ban of crossedBans) {
355
+ add(
356
+ new CannotImportCrossed({
357
+ location,
358
+ importedPath,
359
+ grantPath: ban.grantPath,
360
+ target: ban.target,
361
+ }),
362
+ );
363
+ }
364
+ if (isTestImportedOutsideScriptsAndTests) {
365
+ continue;
366
+ }
367
+ const isTestImportingOutsideTests = isWithin(displayName, TEST_DIRECTORY) && !isTestImport;
368
+ const isExemptFromVisibilityCheck =
369
+ crossedBans.some((ban) => ban.isBuiltIn) ||
370
+ (importedThroughPackage && packageRoot !== packageDirectory) ||
371
+ fileNameOf(importedPath) === PACKAGE_MANIFEST_FILE ||
372
+ isTestImportingOutsideTests;
373
+ const isResolvedIntoAnotherPackage =
374
+ packageRoot !== null && packageRoot !== packageDirectory;
375
+ const hidden = isExemptFromVisibilityCheck
376
+ ? undefined
377
+ : visibilityViolationOf(
378
+ displayName,
379
+ importedPath,
380
+ moduleDirectories,
381
+ location,
382
+ isResolvedIntoAnotherPackage
383
+ ? packagePathOf(path, packageDirectory, packageRoot)
384
+ : undefined,
385
+ );
386
+ if (hidden !== undefined) {
387
+ add(hidden);
388
+ }
389
+ }
390
+ }
391
+ const ignored = new Set(
392
+ yield* ignoredPackagePathsAmong(
393
+ unresolved.map(({ missingPath }) => missingPath),
394
+ packageDirectory,
395
+ ),
396
+ );
397
+ for (const {
398
+ location,
399
+ specifier,
400
+ missingPath,
401
+ isTypeChecked,
402
+ isReportedByNoRequireImports,
403
+ } of unresolved) {
404
+ const isReportedByTheTypeCheckOrNoRequireImports =
405
+ isTypeChecked || isReportedByNoRequireImports;
406
+ if (ignored.has(missingPath)) {
407
+ add(new ImportOfMissingIgnoredFile({ location, specifier, missingPath }));
408
+ } else if (!isReportedByTheTypeCheckOrNoRequireImports) {
409
+ add(new ImportResolvesToNoFile({ location, specifier }));
410
+ }
411
+ }
412
+ if (violations.size > 0) {
413
+ return yield* new ImportBoundariesCrossed({ violations: [...violations.values()] });
414
+ }
415
+ }).pipe(Effect.scoped);
@@ -0,0 +1,117 @@
1
+ import { Effect, FileSystem, Option, Path, Schema } from "effect";
2
+
3
+ import { isFileSpecifier } from "../../../shared/classify-files-by-role.ts";
4
+ import { conditionNamesWith } from "../../../shared/create-the-module-resolver.ts";
5
+ import { enclosingPackageManifestsOf } from "../../../shared/find-named-package-manifests.ts";
6
+ import { ModuleRequestUnresolvable } from "../../../shared/project-config-and-tool-errors.ts";
7
+ import {
8
+ JSON_OBJECT,
9
+ packageManifestObject,
10
+ } from "../../../shared/read-package-manifest-object.ts";
11
+
12
+ const SUBPATH_IMPORT_PREFIX = "#";
13
+ const PATTERN_WILDCARD = "*";
14
+ const DEFAULT_CONDITION = "default";
15
+ const isJsonObject = Schema.is(JSON_OBJECT);
16
+
17
+ const conditionalTarget = (
18
+ value: Schema.Json,
19
+ conditionNames: ReadonlySet<string>,
20
+ ): string | undefined => {
21
+ if (typeof value === "string") {
22
+ return value;
23
+ }
24
+ if (Array.isArray(value)) {
25
+ return value
26
+ .map((item: Schema.Json) => conditionalTarget(item, conditionNames))
27
+ .find((target) => target !== undefined);
28
+ }
29
+ if (!isJsonObject(value)) {
30
+ return;
31
+ }
32
+ const matched = Object.entries(value).find(
33
+ ([condition]) => condition === DEFAULT_CONDITION || conditionNames.has(condition),
34
+ );
35
+ return matched === undefined ? undefined : conditionalTarget(matched[1], conditionNames);
36
+ };
37
+
38
+ const matchedImport = (imports: typeof JSON_OBJECT.Type, request: string) => {
39
+ const exact = imports[request];
40
+ const isExactKey = exact !== undefined && !request.includes(PATTERN_WILDCARD);
41
+ if (isExactKey) {
42
+ return { value: exact, capture: "" };
43
+ }
44
+ const [longest] = Object.keys(imports)
45
+ .flatMap((key) => {
46
+ const [prefix = "", suffix, ...more] = key.split(PATTERN_WILDCARD);
47
+ const matchesPattern =
48
+ suffix !== undefined &&
49
+ more.length === 0 &&
50
+ request.length >= key.length &&
51
+ request.startsWith(prefix) &&
52
+ request.endsWith(suffix);
53
+ return matchesPattern
54
+ ? [{ key, prefix, capture: request.slice(prefix.length, request.length - suffix.length) }]
55
+ : [];
56
+ })
57
+ .toSorted(
58
+ (first, second) =>
59
+ second.prefix.length - first.prefix.length || second.key.length - first.key.length,
60
+ );
61
+ if (longest === undefined) {
62
+ return;
63
+ }
64
+ const value = imports[longest.key];
65
+ return value === undefined ? undefined : { value, capture: longest.capture };
66
+ };
67
+
68
+ const nearestManifestImports = (directory: string, projectDirectory: string) =>
69
+ Effect.gen(function* () {
70
+ const fileSystem = yield* FileSystem.FileSystem;
71
+ for (const manifestFile of enclosingPackageManifestsOf(directory, projectDirectory)) {
72
+ if (yield* fileSystem.exists(manifestFile)) {
73
+ const manifest = yield* Effect.fromResult(
74
+ packageManifestObject(manifestFile, yield* fileSystem.readFileString(manifestFile)),
75
+ );
76
+ const { imports } = manifest;
77
+ return isJsonObject(imports) ? Option.some(imports) : Option.none();
78
+ }
79
+ }
80
+ return Option.none<typeof JSON_OBJECT.Type>();
81
+ });
82
+
83
+ export const packageRequestBehindSubpathImport = ({
84
+ request,
85
+ importingFile,
86
+ customConditions,
87
+ projectDirectory,
88
+ }: {
89
+ readonly request: string;
90
+ readonly importingFile: string;
91
+ readonly customConditions: readonly string[];
92
+ readonly projectDirectory: string;
93
+ }) =>
94
+ Effect.gen(function* () {
95
+ if (!request.startsWith(SUBPATH_IMPORT_PREFIX)) {
96
+ return;
97
+ }
98
+ const path = yield* Path.Path;
99
+ const imports = yield* nearestManifestImports(path.dirname(importingFile), projectDirectory);
100
+ if (Option.isNone(imports)) {
101
+ return;
102
+ }
103
+ const matched = matchedImport(imports.value, request);
104
+ if (matched === undefined) {
105
+ return;
106
+ }
107
+ const target = conditionalTarget(matched.value, new Set(conditionNamesWith(customConditions)));
108
+ if (target === undefined) {
109
+ return;
110
+ }
111
+ const packageRequest = target.replaceAll(PATTERN_WILDCARD, matched.capture);
112
+ return isFileSpecifier(packageRequest) ? undefined : packageRequest;
113
+ }).pipe(
114
+ Effect.mapError(
115
+ (error) => new ModuleRequestUnresolvable({ request, importingFile, reason: error.message }),
116
+ ),
117
+ );
@@ -0,0 +1,65 @@
1
+ import { Array as Arrays, Option } from "effect";
2
+
3
+ import {
4
+ fileNameOf,
5
+ INTERNAL_DIRECTORY_NAME,
6
+ isEntryFileName,
7
+ isWithin,
8
+ } from "../../../../../shared/match-file-names-and-path-prefixes.ts";
9
+ import { directoryOf, enclosingDirectoriesOf } from "../../../shared/classify-files-by-role.ts";
10
+
11
+ export const whatHidesTheImport = (
12
+ importerPath: string,
13
+ importedPath: string,
14
+ moduleDirectories: ReadonlySet<string>,
15
+ otherPackageDirectory: string | undefined,
16
+ ) =>
17
+ Option.getOrUndefined(
18
+ Arrays.findFirst(
19
+ enclosingDirectoriesOf(importedPath),
20
+ (
21
+ directory,
22
+ ): Option.Option<
23
+ | {
24
+ readonly hiddenBy: "plain directory";
25
+ readonly directory: string;
26
+ readonly parent: string;
27
+ }
28
+ | { readonly hiddenBy: "internal"; readonly directory: string; readonly parent: string }
29
+ | { readonly hiddenBy: "module"; readonly directory: string }
30
+ | { readonly hiddenBy: "package"; readonly directory: string }
31
+ > => {
32
+ if (isWithin(importerPath, directory)) {
33
+ return Option.none();
34
+ }
35
+ const isModuleOrPackageDirectory =
36
+ moduleDirectories.has(directory) || directory === otherPackageDirectory;
37
+ if (isModuleOrPackageDirectory) {
38
+ const importsDirectoryEntryFile =
39
+ directoryOf(importedPath) === directory && isEntryFileName(fileNameOf(importedPath));
40
+ if (importsDirectoryEntryFile) {
41
+ return Option.none();
42
+ }
43
+ return Option.some(
44
+ moduleDirectories.has(directory)
45
+ ? ({ hiddenBy: "module", directory } as const)
46
+ : ({ hiddenBy: "package", directory } as const),
47
+ );
48
+ }
49
+ const parent = directoryOf(directory);
50
+ const isImporterTheModuleIndex =
51
+ directoryOf(importerPath) === parent && isEntryFileName(fileNameOf(importerPath));
52
+ const isImporterOutsidePrivateCode =
53
+ fileNameOf(directory) === INTERNAL_DIRECTORY_NAME &&
54
+ moduleDirectories.has(parent) &&
55
+ !isImporterTheModuleIndex;
56
+ if (isImporterOutsidePrivateCode) {
57
+ return Option.some({ hiddenBy: "internal", directory, parent } as const);
58
+ }
59
+ const isImporterOutsideParent = parent !== "" && !isWithin(importerPath, parent);
60
+ return isImporterOutsideParent
61
+ ? Option.some({ hiddenBy: "plain directory", directory, parent } as const)
62
+ : Option.none();
63
+ },
64
+ ),
65
+ );