@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,79 @@
1
+ import { Task } from "@sshkeda/task";
2
+ import { Effect, FileSystem, Path, References, Schema, Stream } from "effect";
3
+ import { parseSync } from "oxc-parser";
4
+
5
+ import { isFileSpecifier, packagePathOf } from "./classify-files-by-role.ts";
6
+ import { moduleRequestsIn } from "./find-module-requests.ts";
7
+ import {
8
+ checkedSourceFiles,
9
+ CUSTOM_CONDITIONS,
10
+ effectiveCompilerOptions,
11
+ } from "./query-the-typescript-project.ts";
12
+ import { resolveModuleRequest } from "./resolve-module-requests.ts";
13
+
14
+ const CHECK_IGNORE_EXIT_CODE_WHEN_NO_PATH_IS_IGNORED = 1;
15
+ export const ignoredPackagePathsAmong = (
16
+ packagePaths: readonly string[],
17
+ packageDirectory: string,
18
+ ) =>
19
+ Effect.gen(function* () {
20
+ const insidePackage = [...new Set(packagePaths)].filter(
21
+ (packagePath) => packagePath !== "" && !packagePath.startsWith(".."),
22
+ );
23
+ if (insidePackage.length === 0) {
24
+ return [];
25
+ }
26
+ const listed = yield* Task.exec("git", ["check-ignore", "--stdin", "-z"], {
27
+ cwd: packageDirectory,
28
+ stdin: Stream.encodeText(
29
+ Stream.make(insidePackage.map((packagePath) => `${packagePath}\0`).join("")),
30
+ ),
31
+ }).pipe(
32
+ Effect.provideService(References.MinimumLogLevel, "Warn"),
33
+ Effect.catchTag("CommandFailed", (failure) =>
34
+ failure.code === CHECK_IGNORE_EXIT_CODE_WHEN_NO_PATH_IS_IGNORED
35
+ ? Effect.succeed("")
36
+ : Effect.fail(failure),
37
+ ),
38
+ );
39
+ return listed.split("\0").filter((ignoredPath) => ignoredPath !== "");
40
+ });
41
+
42
+ export const ignoredFilesImportedIn = (projectFile: string) =>
43
+ Effect.gen(function* () {
44
+ const fileSystem = yield* FileSystem.FileSystem;
45
+ const path = yield* Path.Path;
46
+ const packageDirectory = yield* fileSystem.realPath(path.dirname(projectFile));
47
+ const { customConditions = [] } = yield* Schema.decodeEffect(CUSTOM_CONDITIONS)(
48
+ yield* effectiveCompilerOptions(projectFile),
49
+ );
50
+ const importedPaths: string[] = [];
51
+ for (const displayName of yield* checkedSourceFiles(projectFile)) {
52
+ const importingFile = path.join(packageDirectory, displayName);
53
+ const parsed = parseSync(displayName, yield* fileSystem.readFileString(importingFile));
54
+ for (const { specifier } of moduleRequestsIn(parsed).requests) {
55
+ if (isFileSpecifier(specifier)) {
56
+ const importedFile =
57
+ (yield* resolveModuleRequest({
58
+ request: specifier,
59
+ importingFile,
60
+ customConditions,
61
+ projectDirectory: packageDirectory,
62
+ }))?.file ?? path.resolve(path.dirname(importingFile), specifier);
63
+ importedPaths.push(packagePathOf(path, packageDirectory, importedFile));
64
+ }
65
+ }
66
+ }
67
+ const ignoredFiles: string[] = [];
68
+ for (const ignoredPath of yield* ignoredPackagePathsAmong(importedPaths, packageDirectory)) {
69
+ const absolutePath = path.join(packageDirectory, ignoredPath);
70
+ const ignoredDirectoryIsNoImportedFile = yield* fileSystem.stat(absolutePath).pipe(
71
+ Effect.map((information) => information.type === "Directory"),
72
+ Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(false)),
73
+ );
74
+ if (!ignoredDirectoryIsNoImportedFile) {
75
+ ignoredFiles.push(ignoredPath);
76
+ }
77
+ }
78
+ return ignoredFiles.toSorted();
79
+ });
@@ -0,0 +1,28 @@
1
+ import { Effect, FileSystem, Path } from "effect";
2
+
3
+ import { isScript, SCRIPT_EXTENSIONS } from "./classify-files-by-role.ts";
4
+ import { ignoredFilesImportedIn } from "./list-ignored-files-imported-by-source.ts";
5
+ import { ownedFilesAmong } from "./list-owned-files.ts";
6
+ import { existingPackageFiles } from "./list-package-files.ts";
7
+ import { programFiles } from "./query-the-typescript-project.ts";
8
+
9
+ const SCRIPT_PATHSPECS = SCRIPT_EXTENSIONS.map((extension) => `*${extension}`);
10
+
11
+ export const scriptFiles = (projectFile: string) =>
12
+ Effect.gen(function* () {
13
+ const fileSystem = yield* FileSystem.FileSystem;
14
+ const path = yield* Path.Path;
15
+ const tracked = yield* existingPackageFiles(path.dirname(projectFile), SCRIPT_PATHSPECS);
16
+ const compiled = yield* programFiles(projectFile);
17
+ const imported = yield* Effect.filter(
18
+ (yield* ignoredFilesImportedIn(projectFile)).filter((file) => isScript(file)),
19
+ (file) => fileSystem.exists(path.join(path.dirname(projectFile), file)),
20
+ );
21
+ return [...new Set([...tracked, ...compiled, ...imported])].toSorted();
22
+ });
23
+
24
+ export const lintedFiles = (projectFile: string) =>
25
+ Effect.gen(function* () {
26
+ const path = yield* Path.Path;
27
+ return yield* ownedFilesAmong(path.dirname(projectFile), yield* scriptFiles(projectFile));
28
+ });
@@ -0,0 +1,13 @@
1
+ import { Effect } from "effect";
2
+
3
+ import { generatedPathsOf } from "../../../shared/record-and-grant-permissions-by-path.ts";
4
+ import { loadedLintConfigIn } from "./load-the-lint-config.ts";
5
+
6
+ export const ownedFilesAmong = (directory: string, files: readonly string[]) =>
7
+ loadedLintConfigIn(directory).pipe(
8
+ Effect.map((grants) => {
9
+ const generated = generatedPathsOf(grants);
10
+ return files.filter((file) => !generated.has(file));
11
+ }),
12
+ Effect.catchTag("LintConfigRefused", () => Effect.succeed(files)),
13
+ );
@@ -0,0 +1,66 @@
1
+ import { Task } from "@sshkeda/task";
2
+ import { Effect, FileSystem, Option, Path, References } from "effect";
3
+
4
+ import { enclosingDirectoriesOf } from "./classify-files-by-role.ts";
5
+ import { PACKAGE_MANIFEST_FILE } from "./find-named-package-manifests.ts";
6
+ import { namedPackageManifestAt } from "./read-named-package-manifests.ts";
7
+
8
+ const isNamedPackageDirectory = (directory: string) =>
9
+ Path.Path.use((path) =>
10
+ namedPackageManifestAt(path.join(directory, PACKAGE_MANIFEST_FILE)).pipe(
11
+ Effect.map(Option.isSome),
12
+ ),
13
+ );
14
+
15
+ export const nestedPackageDirectoriesAmong = (
16
+ packageDirectory: string,
17
+ relativePaths: readonly string[],
18
+ ) =>
19
+ Effect.gen(function* () {
20
+ const path = yield* Path.Path;
21
+ const nestedPackageDirectories = yield* Effect.filter(
22
+ new Set(relativePaths.flatMap((relativePath) => enclosingDirectoriesOf(relativePath))),
23
+ (directory) => isNamedPackageDirectory(path.join(packageDirectory, directory)),
24
+ { concurrency: "unbounded" },
25
+ );
26
+ return nestedPackageDirectories.toSorted();
27
+ });
28
+
29
+ export const isInsideAnyDirectory = (relativePath: string, directories: readonly string[]) =>
30
+ directories.some((directory) => relativePath.startsWith(`${directory}/`));
31
+
32
+ const existingListedFiles = (packageDirectory: string, pathspecs: readonly string[]) =>
33
+ Effect.gen(function* () {
34
+ const fileSystem = yield* FileSystem.FileSystem;
35
+ const path = yield* Path.Path;
36
+ const listed = yield* Task.exec(
37
+ "git",
38
+ ["ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", ...pathspecs],
39
+ { cwd: packageDirectory },
40
+ ).pipe(Effect.provideService(References.MinimumLogLevel, "Warn"));
41
+ return yield* Effect.filter(
42
+ new Set(listed.split("\0").filter((file) => file !== "")),
43
+ (file) => fileSystem.exists(path.join(packageDirectory, file)),
44
+ { concurrency: "unbounded" },
45
+ );
46
+ });
47
+
48
+ export const listedPackageFiles = (packageDirectory: string, pathspecs: readonly string[]) =>
49
+ Effect.gen(function* () {
50
+ const existing = yield* existingListedFiles(packageDirectory, pathspecs);
51
+ const nestedPackageDirectories = yield* nestedPackageDirectoriesAmong(
52
+ packageDirectory,
53
+ existing,
54
+ );
55
+ return {
56
+ packageFiles: existing
57
+ .filter((file) => !isInsideAnyDirectory(file, nestedPackageDirectories))
58
+ .toSorted(),
59
+ nestedPackageDirectories,
60
+ };
61
+ });
62
+
63
+ export const existingPackageFiles = (packageDirectory: string, pathspecs: readonly string[]) =>
64
+ listedPackageFiles(packageDirectory, pathspecs).pipe(
65
+ Effect.map(({ packageFiles }) => packageFiles),
66
+ );
@@ -0,0 +1,176 @@
1
+ import { Effect, FileSystem, Path, Result } from "effect";
2
+ import type { ArrayExpressionElement, Expression } from "oxc-parser";
3
+
4
+ import { MalformedGrant } from "../../../shared/permission-grant-errors.ts";
5
+ import {
6
+ GENERATED,
7
+ recordedGrantsOf,
8
+ } from "../../../shared/record-and-grant-permissions-by-path.ts";
9
+ import { LINT_CONFIG, parsedConfigFileIn } from "./parse-config-files-that-import-from-check.ts";
10
+ import {
11
+ LintConfigArgumentNotLiteral,
12
+ LintConfigKeyRepeated,
13
+ LintConfigRefused,
14
+ } from "./project-config-and-tool-errors.ts";
15
+
16
+ const literalStringOf = (node: ArrayExpressionElement) => {
17
+ if (node?.type !== "Literal") {
18
+ return;
19
+ }
20
+ const { value } = node;
21
+ return typeof value === "string" ? value : undefined;
22
+ };
23
+
24
+ const literalKeysOf = (node: Expression) =>
25
+ node.type === "ObjectExpression"
26
+ ? node.properties.flatMap((property) => {
27
+ if (property.type !== "Property") {
28
+ return [];
29
+ }
30
+ const isPlainKeyValueProperty =
31
+ property.kind === "init" && !property.computed && !property.method && !property.shorthand;
32
+ if (!isPlainKeyValueProperty) {
33
+ return [];
34
+ }
35
+ if (property.key.type === "Identifier") {
36
+ return [{ name: property.key.name, value: property.value }];
37
+ }
38
+ const literalKeyValue = property.key.type === "Literal" ? property.key.value : undefined;
39
+ return typeof literalKeyValue === "string"
40
+ ? [{ name: literalKeyValue, value: property.value }]
41
+ : [];
42
+ })
43
+ : [];
44
+
45
+ const isLiteralObject = (node: Expression, isLiteralValue: (value: Expression) => boolean) =>
46
+ node.type === "ObjectExpression" &&
47
+ literalKeysOf(node).length === node.properties.length &&
48
+ literalKeysOf(node).every((key) => isLiteralValue(key.value));
49
+
50
+ const isLiteralReasons = (node: Expression) =>
51
+ isLiteralObject(node, (reason) => literalStringOf(reason) !== undefined);
52
+
53
+ const isLiteralGrantList = (node: Expression) =>
54
+ node.type === "ArrayExpression" &&
55
+ node.elements.every((element) => {
56
+ const isReasons = element?.type === "ObjectExpression" && isLiteralReasons(element);
57
+ return isReasons || literalStringOf(element) !== undefined;
58
+ });
59
+
60
+ const isLiteralLintConfigArgument = (node: Expression) =>
61
+ isLiteralObject(node, (entry) => isLiteralObject(entry, isLiteralGrantList));
62
+
63
+ const literalGrantItemOf = (element: ArrayExpressionElement) => {
64
+ if (element?.type === "ObjectExpression") {
65
+ return [
66
+ Object.fromEntries(
67
+ literalKeysOf(element).flatMap(({ name, value }) => {
68
+ const reason = literalStringOf(value);
69
+ return reason === undefined ? [] : [[name, reason]];
70
+ }),
71
+ ),
72
+ ];
73
+ }
74
+ const literal = literalStringOf(element);
75
+ return literal === undefined ? [] : [literal];
76
+ };
77
+
78
+ const literalPermissionsOf = (node: Expression) =>
79
+ Object.fromEntries(
80
+ literalKeysOf(node).map((entry) => [
81
+ entry.name,
82
+ Object.fromEntries(
83
+ literalKeysOf(entry.value).map((list) => [
84
+ list.name,
85
+ list.value.type === "ArrayExpression"
86
+ ? list.value.elements.flatMap((element) => [...literalGrantItemOf(element)])
87
+ : [],
88
+ ]),
89
+ ),
90
+ ]),
91
+ );
92
+
93
+ const objectsIn = (node: ArrayExpressionElement): readonly Expression[] => {
94
+ if (node?.type === "ArrayExpression") {
95
+ return node.elements.flatMap((element) => objectsIn(element));
96
+ }
97
+ if (node?.type !== "ObjectExpression") {
98
+ return [];
99
+ }
100
+ return [node, ...literalKeysOf(node).flatMap(({ value }) => objectsIn(value))];
101
+ };
102
+
103
+ const repeatedKeysIn = (argument: Expression) =>
104
+ objectsIn(argument).flatMap((object) => {
105
+ const names = literalKeysOf(object).map(({ name }) => name);
106
+ const repeated = names.filter((name, index) => names.indexOf(name) !== index);
107
+ return [...new Set(repeated)].map((key) => ({ object, key }));
108
+ });
109
+
110
+ export const lintConfigOf = (parsed: Effect.Success<ReturnType<typeof parsedConfigFileIn>>) => {
111
+ if (Result.isFailure(parsed)) {
112
+ return { violations: parsed.failure };
113
+ }
114
+ const { call, violations, lineOf } = parsed.success;
115
+ if (call === undefined) {
116
+ return { violations };
117
+ }
118
+ const [argument] = call.arguments;
119
+ const isLiteralArgument =
120
+ argument !== undefined &&
121
+ argument.type !== "SpreadElement" &&
122
+ isLiteralLintConfigArgument(argument);
123
+ if (!isLiteralArgument) {
124
+ return {
125
+ violations: [
126
+ ...violations,
127
+ new LintConfigArgumentNotLiteral({ location: lineOf(call.start) }),
128
+ ],
129
+ };
130
+ }
131
+ const repeatedKeys = repeatedKeysIn(argument).map(
132
+ ({ object, key }) => new LintConfigKeyRepeated({ location: lineOf(object.start), key }),
133
+ );
134
+ if (violations.length + repeatedKeys.length > 0) {
135
+ return { violations: [...violations, ...repeatedKeys] };
136
+ }
137
+ return { permissionsByPath: literalPermissionsOf(argument) };
138
+ };
139
+
140
+ export const loadedLintConfigIn = (directory: string) =>
141
+ Effect.gen(function* () {
142
+ const parsed = lintConfigOf(yield* parsedConfigFileIn(directory, LINT_CONFIG));
143
+ if ("violations" in parsed) {
144
+ return yield* new LintConfigRefused({ violations: parsed.violations });
145
+ }
146
+ const recorded = recordedGrantsOf(parsed.permissionsByPath);
147
+ if (recorded.grants === undefined) {
148
+ return yield* new LintConfigRefused({ violations: recorded.violations });
149
+ }
150
+ const fileSystem = yield* FileSystem.FileSystem;
151
+ const path = yield* Path.Path;
152
+ const fileGrants = recorded.grants.flatMap((grant) =>
153
+ grant.allow
154
+ .filter((permission) => permission === GENERATED)
155
+ .map((permission) => ({ file: grant.path, permission })),
156
+ );
157
+ const violations = yield* Effect.forEach(fileGrants, ({ file, permission }) =>
158
+ Effect.gen(function* () {
159
+ const absolute = path.join(directory, file);
160
+ const exists = yield* fileSystem.exists(absolute);
161
+ const isFile = exists && (yield* fileSystem.stat(absolute)).type === "File";
162
+ return isFile
163
+ ? []
164
+ : [
165
+ new MalformedGrant({
166
+ issuePath: file,
167
+ issueMessage: `grants ${permission}, but is not an existing file`,
168
+ }),
169
+ ];
170
+ }),
171
+ );
172
+ if (violations.flat().length > 0) {
173
+ return yield* new LintConfigRefused({ violations: violations.flat() });
174
+ }
175
+ return recorded.grants;
176
+ });
@@ -0,0 +1,88 @@
1
+ import { Effect, FileSystem, Path, Result, Schema } from "effect";
2
+
3
+ import { normalizedPath, PATCH } from "../../../shared/record-and-grant-permissions-by-path.ts";
4
+ import type { PERMISSION_NAMES } from "../../../shared/record-and-grant-permissions-by-path.ts";
5
+ import { directoryOf } from "./classify-files-by-role.ts";
6
+ import { PACKAGE_MANIFEST_FILE } from "./find-named-package-manifests.ts";
7
+ import { packageManifestObject } from "./read-package-manifest-object.ts";
8
+ import type { JSON_OBJECT } from "./read-package-manifest-object.ts";
9
+
10
+ export const PATCHED_DEPENDENCIES_FIELD = "patchedDependencies";
11
+ const PATCHED_DEPENDENCIES = Schema.Record(Schema.String, Schema.String);
12
+ const PATCH_FILE_EXTENSION = ".patch";
13
+ const MANIFEST_FAILURES_ARE_REPORTED_BY_MANIFEST_VIOLATIONS = {} as const;
14
+
15
+ const BUN_PATCH_FILE_NAME_ESCAPES = new Map([
16
+ ["/", "%2F"],
17
+ ["\\", "%5c"],
18
+ [" ", "%20"],
19
+ ["\n", "%0A"],
20
+ ["\r", "%0D"],
21
+ ["\t", "%09"],
22
+ [":", "%3A"],
23
+ ["?", "%3F"],
24
+ ["*", "%2A"],
25
+ ['"', "%22"],
26
+ ["<", "%3C"],
27
+ [">", "%3E"],
28
+ ["|", "%7C"],
29
+ ]);
30
+ const BUN_PATCH_FILE_NAME_ESCAPED_CHARACTER = /[/\\ \n\r\t:?*"<>|]/gu;
31
+ const URL_AUTHORITY = /^(?<scheme>[^:]*:\/\/)(?<authority>[^/?#]*)(?<rest>[\s\S]*)$/u;
32
+
33
+ const withoutUrlCredentials = (key: string) => {
34
+ const groups = URL_AUTHORITY.exec(key)?.groups;
35
+ if (groups === undefined) {
36
+ return key;
37
+ }
38
+ const { scheme = "", authority = "", rest = "" } = groups;
39
+ const host = authority.slice(authority.lastIndexOf("@") + 1);
40
+ const queryStart = rest.includes("?") ? rest.indexOf("?") : rest.length;
41
+ const query = rest.slice(queryStart);
42
+ const fragment = query.includes("#") ? query.slice(query.indexOf("#")) : "";
43
+ return `${scheme}${host}${rest.slice(0, queryStart)}${fragment}`;
44
+ };
45
+
46
+ export const bunPatchFileNameOf = (dependency: string) =>
47
+ `${withoutUrlCredentials(dependency)}${PATCH_FILE_EXTENSION}`.replaceAll(
48
+ BUN_PATCH_FILE_NAME_ESCAPED_CHARACTER,
49
+ (character) => BUN_PATCH_FILE_NAME_ESCAPES.get(character) ?? character,
50
+ );
51
+
52
+ export const patchedDependenciesOf = (manifest: typeof JSON_OBJECT.Type) =>
53
+ Schema.decodeUnknownResult(PATCHED_DEPENDENCIES)(manifest[PATCHED_DEPENDENCIES_FIELD] ?? {});
54
+
55
+ export const listedPatchesOf = (manifest: typeof JSON_OBJECT.Type) =>
56
+ Object.entries(Result.getOrElse(patchedDependenciesOf(manifest), () => ({}))).map(
57
+ ([dependency, patchPath]) => ({ dependency, patchPath: normalizedPath(patchPath) }),
58
+ );
59
+
60
+ export const rootManifestIn = (directory: string, paths: readonly string[]) =>
61
+ Effect.gen(function* () {
62
+ if (!paths.includes(PACKAGE_MANIFEST_FILE)) {
63
+ return {};
64
+ }
65
+ const fileSystem = yield* FileSystem.FileSystem;
66
+ const pathModule = yield* Path.Path;
67
+ const text = yield* fileSystem.readFileString(
68
+ pathModule.join(directory, PACKAGE_MANIFEST_FILE),
69
+ );
70
+ return Result.getOrElse(
71
+ packageManifestObject(PACKAGE_MANIFEST_FILE, text),
72
+ () => MANIFEST_FAILURES_ARE_REPORTED_BY_MANIFEST_VIOLATIONS,
73
+ );
74
+ });
75
+
76
+ export const isGrantedPatchFile = (
77
+ path: string,
78
+ grants: readonly {
79
+ readonly path: string;
80
+ readonly allow?: readonly (typeof PERMISSION_NAMES)[number][];
81
+ }[],
82
+ ) =>
83
+ path.endsWith(PATCH_FILE_EXTENSION) &&
84
+ grants.some(
85
+ (grant) =>
86
+ grant.allow?.includes(PATCH) === true &&
87
+ (grant.path === path || grant.path === directoryOf(path)),
88
+ );