@sshkeda/check 3.0.0 → 4.0.1

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 (35) hide show
  1. package/README.md +5 -41
  2. package/docs/how-to-grant-a-permission.md +28 -0
  3. package/docs/how-to-make-check-pass.md +4 -31
  4. package/package.json +2 -2
  5. package/scripts/check.ts +2 -3
  6. package/src/internal/ban-fixed-values-in-recoveries.ts +1 -1
  7. package/src/lib/project-directory/index.ts +0 -1
  8. package/src/lib/project-directory/internal/read-the-project-directory.ts +1 -5
  9. package/src/lib/tasks/internal/declare-the-check-task.ts +6 -6
  10. package/src/lib/tasks/internal/declare-the-checker-queries-task.ts +4 -4
  11. package/src/lib/tasks/internal/declare-the-typed-checks-task.ts +4 -4
  12. package/src/lib/tasks/lib/check-effect-diagnostics-with-effect-tsgo/index.ts +4 -4
  13. package/src/lib/tasks/lib/confine-layer-provides-to-program-starts/internal/find-layer-provides-outside-program-starts.ts +15 -1
  14. package/src/lib/tasks/lib/confine-layer-provides-to-program-starts/internal/resolve-imported-package-apis.ts +1 -2
  15. package/src/lib/tasks/lib/detect-duplicate-functions/index.ts +4 -4
  16. package/src/lib/tasks/lib/enforce-file-layout/index.ts +4 -4
  17. package/src/lib/tasks/lib/enforce-file-layout/internal/file-layout-errors.ts +7 -29
  18. package/src/lib/tasks/lib/enforce-file-layout/internal/find-file-layout-violations.ts +14 -181
  19. package/src/lib/tasks/lib/enforce-file-types/index.ts +4 -4
  20. package/src/lib/tasks/lib/format-with-bun-fmt/internal/declare-the-formatting-task.ts +28 -17
  21. package/src/lib/tasks/lib/lint-with-oxlint/index.ts +4 -4
  22. package/src/lib/tasks/lib/refuse-disable-directives/index.ts +4 -4
  23. package/src/lib/tasks/lib/require-type-checking-every-linted-file/index.ts +4 -4
  24. package/src/lib/tasks/lib/type-check-with-bun-check/index.ts +4 -4
  25. package/src/lib/tasks/shared/check-each-nested-package.ts +2 -0
  26. package/src/lib/tasks/shared/declare-lint-config-task.ts +4 -4
  27. package/src/lib/tasks/shared/declare-start-directory-task.ts +40 -0
  28. package/src/lib/tasks/shared/declare-typescript-config-task.ts +4 -4
  29. package/src/lib/tasks/shared/project-config-and-tool-errors.ts +9 -0
  30. package/src/lib/tasks/shared/query-the-typescript-project.ts +10 -15
  31. package/src/lib/tasks/shared/watch-the-typescript-api-process.ts +177 -0
  32. package/src/shared/bans-each-permission-lifts.ts +0 -7
  33. package/src/shared/record-and-grant-permissions-by-path.ts +1 -3
  34. package/src/lib/tasks/internal/verify-where-check-was-started.ts +0 -50
  35. package/src/lib/tasks/lib/enforce-file-layout/internal/resolve-task-imports.ts +0 -178
@@ -0,0 +1,177 @@
1
+ import { Context, Deferred, Effect, Option, Predicate, Schema } from "effect";
2
+ import type { Duration } from "effect";
3
+ import { API } from "typescript/unstable/async";
4
+ import type { InternalAPI } from "typescript/unstable/async";
5
+
6
+ import {
7
+ TypeScriptApiFailed,
8
+ TypeScriptApiProcessStopped,
9
+ } from "./project-config-and-tool-errors.ts";
10
+
11
+ const TYPESCRIPT_REQUEST_DEADLINE = "10 minutes";
12
+
13
+ const EXIT_DEADLINE = "10 seconds";
14
+
15
+ const STARTING = "start";
16
+
17
+ const CLIENT_CHANGED = "the TypeScript API client no longer exposes the process Check watches";
18
+
19
+ const CLOSED = "the TypeScript API was closed";
20
+
21
+ const OUTPUT_CLOSED = "the TypeScript API process closed its output";
22
+
23
+ const TERMINATING_SIGNAL = "SIGKILL";
24
+
25
+ const API_CLIENT_FIELD = "client";
26
+
27
+ const CLIENT_PROCESS_FIELD = "process";
28
+
29
+ export const TypeScriptApiLaunch = Context.Reference<{
30
+ readonly tsserverPath?: string;
31
+ readonly requestDeadline: `${number} ${Duration.Unit}`;
32
+ }>("@sshkeda/check/TypeScriptApiLaunch", {
33
+ defaultValue: () => ({ requestDeadline: TYPESCRIPT_REQUEST_DEADLINE }),
34
+ });
35
+
36
+ const CLIENT_MEMBERS = [
37
+ "connect",
38
+ "apiRequest",
39
+ "close",
40
+ ] as const satisfies readonly (keyof ConstructorParameters<typeof InternalAPI>[0])[];
41
+
42
+ const TYPESCRIPT_API_CLIENT = Schema.declare(
43
+ (value): value is ConstructorParameters<typeof InternalAPI>[0] =>
44
+ CLIENT_MEMBERS.every((member) => Predicate.hasProperty(value, member)),
45
+ );
46
+
47
+ const PROCESS_MEMBERS = ["once", "on", "kill", "stdout"] as const;
48
+
49
+ const isWatchableProcess = Schema.is(
50
+ Schema.declare(
51
+ (
52
+ value,
53
+ ): value is {
54
+ readonly stdout: { once(event: "close", listener: () => void): void } | null;
55
+ once(
56
+ event: "exit",
57
+ listener: (code: number | null, signal: NodeJS.Signals | null) => void,
58
+ ): void;
59
+ on(event: "error", listener: (error: Error) => void): void;
60
+ kill(signal: NodeJS.Signals): boolean;
61
+ } => PROCESS_MEMBERS.every((member) => Predicate.hasProperty(value, member)),
62
+ ),
63
+ );
64
+
65
+ const stopWith = (
66
+ stopped: Deferred.Deferred<never, TypeScriptApiProcessStopped>,
67
+ child: { kill(signal: NodeJS.Signals): boolean },
68
+ reason: string,
69
+ ) => {
70
+ Deferred.doneUnsafe(stopped, Effect.fail(new TypeScriptApiProcessStopped({ reason })));
71
+ child.kill(TERMINATING_SIGNAL);
72
+ };
73
+
74
+ const exitReason = (code: number | null, signal: NodeJS.Signals | null, outputClosed: boolean) => {
75
+ if (code !== null) {
76
+ return `the TypeScript API process exited with code ${code}`;
77
+ }
78
+ return outputClosed ? OUTPUT_CLOSED : `the TypeScript API process exited on signal ${signal}`;
79
+ };
80
+
81
+ const watchedProcess = (
82
+ client: ConstructorParameters<typeof InternalAPI>[0],
83
+ stopped: Deferred.Deferred<never, TypeScriptApiProcessStopped>,
84
+ exited: Deferred.Deferred<void>,
85
+ ) => {
86
+ const child: unknown = client[CLIENT_PROCESS_FIELD];
87
+ if (!isWatchableProcess(child)) {
88
+ return client.close().then(() => Option.none());
89
+ }
90
+ const output = { closed: false };
91
+ child.once("exit", (code, signal) => {
92
+ stopWith(stopped, child, exitReason(code, signal, output.closed));
93
+ Deferred.doneUnsafe(exited, Effect.void);
94
+ });
95
+ child.on("error", (error) => {
96
+ stopWith(stopped, child, `the TypeScript API process failed: ${error.message}`);
97
+ });
98
+ child.stdout?.once("close", () => {
99
+ output.closed = true;
100
+ child.kill(TERMINATING_SIGNAL);
101
+ });
102
+ return Promise.resolve(Option.some(child));
103
+ };
104
+
105
+ const answered = <Answer>(
106
+ stopped: Deferred.Deferred<never, TypeScriptApiProcessStopped>,
107
+ child: Parameters<typeof stopWith>[1],
108
+ requestDeadline: `${number} ${Duration.Unit}`,
109
+ request: () => Promise<Answer>,
110
+ ) =>
111
+ Effect.gen(function* () {
112
+ if (yield* Deferred.isDone(stopped)) {
113
+ return yield* Deferred.await(stopped);
114
+ }
115
+ return yield* Effect.raceFirst(Effect.promise(request), Deferred.await(stopped)).pipe(
116
+ Effect.timeoutOrElse({
117
+ duration: requestDeadline,
118
+ orElse: () =>
119
+ Effect.sync(() => {
120
+ stopWith(
121
+ stopped,
122
+ child,
123
+ `the TypeScript API process did not answer within ${requestDeadline}`,
124
+ );
125
+ }).pipe(Effect.andThen(Deferred.await(stopped))),
126
+ }),
127
+ );
128
+ });
129
+
130
+ const startedSession = (sourceTextOverrides: ReadonlyMap<string, string>) =>
131
+ Effect.gen(function* () {
132
+ const { requestDeadline, ...spawnOptions } = yield* TypeScriptApiLaunch;
133
+ const api = new API(
134
+ sourceTextOverrides.size === 0
135
+ ? spawnOptions
136
+ : { ...spawnOptions, fs: { readFile: (fileName) => sourceTextOverrides.get(fileName) } },
137
+ );
138
+ const client = yield* Schema.decodeUnknownEffect(TYPESCRIPT_API_CLIENT)(
139
+ api[API_CLIENT_FIELD],
140
+ ).pipe(
141
+ Effect.mapError(
142
+ () => new TypeScriptApiFailed({ operation: STARTING, reason: CLIENT_CHANGED }),
143
+ ),
144
+ );
145
+ const stopped = yield* Deferred.make<never, TypeScriptApiProcessStopped>();
146
+ const exited = yield* Deferred.make<void>();
147
+ const watched = yield* Effect.tryPromise({
148
+ try: () => client.connect().then(() => watchedProcess(client, stopped, exited)),
149
+ catch: (cause) => new TypeScriptApiFailed({ operation: STARTING, reason: String(cause) }),
150
+ });
151
+ if (Option.isNone(watched)) {
152
+ return yield* new TypeScriptApiFailed({ operation: STARTING, reason: CLIENT_CHANGED });
153
+ }
154
+ const child = watched.value;
155
+ const runPromise = Effect.runPromiseWith(yield* Effect.context());
156
+ const send = client.apiRequest.bind(client);
157
+ client.apiRequest = <Answer>(...request: Parameters<typeof send>) =>
158
+ runPromise(answered(stopped, child, requestDeadline, () => send<Answer>(...request)));
159
+ return { api, client, child, stopped, exited };
160
+ });
161
+
162
+ const closedSession = ({
163
+ client,
164
+ child,
165
+ stopped,
166
+ exited,
167
+ }: Effect.Success<ReturnType<typeof startedSession>>) =>
168
+ Effect.gen(function* () {
169
+ stopWith(stopped, child, CLOSED);
170
+ yield* Effect.promise(() => client.close());
171
+ yield* Deferred.await(exited).pipe(Effect.timeoutOption(EXIT_DEADLINE));
172
+ });
173
+
174
+ export const openedApi = (sourceTextOverrides: ReadonlyMap<string, string>) =>
175
+ Effect.acquireRelease(startedSession(sourceTextOverrides), closedSession).pipe(
176
+ Effect.map(({ api }) => api),
177
+ );
@@ -61,7 +61,6 @@ export const isDeclaredSync = (name: string) =>
61
61
  export const TASK_PACKAGE = "@sshkeda/task";
62
62
  export const TASK_NAMESPACE_EXPORT = "Task";
63
63
  export const TASK_MAKE_MEMBER = "make";
64
- export const TASK_MAIN_MEMBER = "main";
65
64
 
66
65
  export const IMPORT_META = "import.meta";
67
66
 
@@ -108,7 +107,6 @@ const CREATE_REQUIRE_IMPORTS = ["createRequire", "Module.createRequire"] as cons
108
107
  export const CREATED_REQUIRE_USAGE = "a require createRequire returns";
109
108
  export const CREATE_REQUIRE_VALUE_USAGE = "createRequire used other than by a call";
110
109
 
111
- export const SCRIPT = "script";
112
110
  export const TRUSTS_UNVERIFIED_TYPES = "trustsUnverifiedTypes";
113
111
  export const WRITES_TO_THE_TERMINAL = "writesToTheTerminal";
114
112
  export const READS_CONFIG = "readsConfig";
@@ -388,11 +386,6 @@ export const PERMISSION_BANS = {
388
386
  memberNamesBan([...SYNC_READS, ...SYNC_WRITES]),
389
387
  ],
390
388
  },
391
- [SCRIPT]: {
392
- ruleName: "no-task-main",
393
- message: "{{usage}} runs tasks outside a script",
394
- bans: [importsBan(TASK_PACKAGE, [`${TASK_NAMESPACE_EXPORT}.${TASK_MAIN_MEMBER}`])],
395
- },
396
389
  };
397
390
 
398
391
  export const PERMISSION_BAN_NAMES = Record.keys(PERMISSION_BANS);
@@ -8,7 +8,6 @@ import {
8
8
  PERMISSION_BANS,
9
9
  READS_CONFIG,
10
10
  RULES_EACH_PERMISSION_LIFTS,
11
- SCRIPT,
12
11
  SHORT_NAMES,
13
12
  TRUSTS_UNVERIFIED_TYPES,
14
13
  UNUSED_GRANT_REPORTED,
@@ -62,7 +61,7 @@ export const PERMISSION_NAMES = [
62
61
 
63
62
  const RETIRED_PERMISSIONS = new Map([
64
63
  ["errors", "error classes may be declared in any file"],
65
- [SCRIPT, `files directly in ${SCRIPTS_DIRECTORY}/ run tasks`],
64
+ ["script", `files directly in ${SCRIPTS_DIRECTORY}/ run tasks`],
66
65
  ]);
67
66
 
68
67
  export const isMarkdown = (path: string) =>
@@ -363,7 +362,6 @@ export const rulesACodeGrantChanges = (
363
362
  const SCRIPTS_OVERRIDE = {
364
363
  files: [`./${SCRIPTS_DIRECTORY}/*`],
365
364
  rules: {
366
- [permissionBanRuleId(SCRIPT)]: "off",
367
365
  "sshkeda/no-re-exports": ["error", { defaultExportOfAnImport: "allowed" }],
368
366
  },
369
367
  } as const;
@@ -1,50 +0,0 @@
1
- import { Task } from "@sshkeda/task";
2
- import { Effect, FileSystem, Path, References, Schema } from "effect";
3
-
4
- import { givenArguments, projectDirectory } from "../../project-directory/index.ts";
5
- import { quietViolations } from "../shared/print-failures-and-keep-detail-in-the-trace.ts";
6
-
7
- const PACKAGE_MANIFEST_FILE = "package.json";
8
-
9
- class ArgumentsNotAccepted extends Schema.TaggedError<ArgumentsNotAccepted>()(
10
- "ArgumentsNotAccepted",
11
- { givenArguments: Schema.Array(Schema.String) },
12
- ) {
13
- public override get message() {
14
- return `check takes no arguments, and was given ${this.givenArguments.join(" ")}`;
15
- }
16
- }
17
-
18
- class PackageManifestMissing extends Schema.TaggedError<PackageManifestMissing>()(
19
- "PackageManifestMissing",
20
- { directory: Schema.String },
21
- ) {
22
- public override get message() {
23
- return `${this.directory} has no ${PACKAGE_MANIFEST_FILE}`;
24
- }
25
- }
26
-
27
- class RepositoryNotFound extends Schema.TaggedError<RepositoryNotFound>()("RepositoryNotFound", {
28
- directory: Schema.String,
29
- }) {
30
- public override get message() {
31
- return `${this.directory} is not inside a git repository`;
32
- }
33
- }
34
-
35
- export const verifyWhereCheckWasStarted = Effect.gen(function* () {
36
- const fileSystem = yield* FileSystem.FileSystem;
37
- const path = yield* Path.Path;
38
- const given = yield* givenArguments;
39
- if (given.length > 0) {
40
- return yield* new ArgumentsNotAccepted({ givenArguments: given });
41
- }
42
- const directory = path.resolve(yield* projectDirectory);
43
- if (!(yield* fileSystem.exists(path.join(directory, PACKAGE_MANIFEST_FILE)))) {
44
- return yield* new PackageManifestMissing({ directory });
45
- }
46
- yield* Task.exec("git", ["rev-parse", "--show-toplevel"], { cwd: directory }).pipe(
47
- Effect.provideService(References.MinimumLogLevel, "Warn"),
48
- Effect.catchTag("CommandFailed", () => Effect.fail(new RepositoryNotFound({ directory }))),
49
- );
50
- }).pipe(quietViolations("check"));
@@ -1,178 +0,0 @@
1
- import { Effect, FileSystem } from "effect";
2
- import { parseSync, Visitor } from "oxc-parser";
3
- import type { ExportSpecifier, Expression, ParseResult } from "oxc-parser";
4
-
5
- import {
6
- TASK_MAIN_MEMBER,
7
- TASK_MAKE_MEMBER,
8
- TASK_PACKAGE,
9
- } from "../../../../../shared/bans-each-permission-lifts.ts";
10
- import {
11
- directoryOf,
12
- isRootSupportFile,
13
- isScript,
14
- isTopLevelScript,
15
- } from "../../../shared/classify-files-by-role.ts";
16
- import { resolveModuleRequest } from "../../../shared/resolve-module-requests.ts";
17
-
18
- const exportNameOf = (name: ExportSpecifier["local"]) =>
19
- name.type === "Identifier" ? name.name : name.value;
20
-
21
- const candidateImportRoots = (parsed: ParseResult) => {
22
- const names = new Set<string>();
23
- const remember = (expression: Expression) => {
24
- if (expression.type === "Identifier") {
25
- names.add(expression.name);
26
- return;
27
- }
28
- const isTaskMember =
29
- expression.type === "MemberExpression" &&
30
- !expression.computed &&
31
- expression.property.type === "Identifier" &&
32
- [TASK_MAKE_MEMBER, TASK_MAIN_MEMBER].includes(expression.property.name);
33
- if (!isTaskMember) {
34
- return;
35
- }
36
- const { object } = expression;
37
- const root = object.type === "MemberExpression" ? object.object : object;
38
- if (root.type === "Identifier") {
39
- names.add(root.name);
40
- }
41
- };
42
- new Visitor({
43
- CallExpression(node) {
44
- remember(node.callee);
45
- },
46
- VariableDeclarator({ init: initializer }) {
47
- if (initializer !== null) {
48
- remember(initializer);
49
- }
50
- },
51
- }).visit(parsed.program);
52
- return names;
53
- };
54
-
55
- export const taskImportsIn = (file: string, text: string, directory: string) =>
56
- Effect.gen(function* () {
57
- const fileSystem = yield* FileSystem.FileSystem;
58
- const projectRoot = yield* fileSystem.realPath(directory);
59
- const taskExportFrom = (
60
- importingFile: string,
61
- request: string,
62
- members: readonly string[],
63
- seen: ReadonlySet<string> = new Set(),
64
- ): Effect.Effect<
65
- readonly string[] | undefined,
66
- | Effect.Error<ReturnType<typeof fileSystem.readFileString>>
67
- | Effect.Error<ReturnType<typeof resolveModuleRequest>>,
68
- Effect.Services<ReturnType<typeof resolveModuleRequest>>
69
- > =>
70
- Effect.gen(function* () {
71
- if (request === TASK_PACKAGE) {
72
- return members;
73
- }
74
- const target = yield* resolveModuleRequest({
75
- importingFile,
76
- request,
77
- customConditions: [],
78
- projectDirectory: directory,
79
- });
80
- if (target === undefined) {
81
- return;
82
- }
83
- const isTaskDependency =
84
- target.packageName === TASK_PACKAGE && target.packageRoot !== projectRoot;
85
- if (isTaskDependency) {
86
- return members;
87
- }
88
- const key = `${target.file}\0${members.join(".")}`;
89
- if (seen.has(key)) {
90
- return;
91
- }
92
- const followed = new Set([...seen, key]);
93
- const parsed = parseSync(target.file, yield* fileSystem.readFileString(target.file));
94
- const [name, ...rest] = members;
95
- if (name === undefined) {
96
- return;
97
- }
98
- for (const statement of parsed.program.body) {
99
- if (statement.type === "ExportNamedDeclaration") {
100
- if (statement.exportKind === "type") {
101
- continue;
102
- }
103
- const specifier = statement.specifiers.find(
104
- (entry) => exportNameOf(entry.exported) === name && entry.exportKind !== "type",
105
- );
106
- if (specifier !== undefined) {
107
- const localName = exportNameOf(specifier.local);
108
- if (statement.source !== null) {
109
- return yield* taskExportFrom(
110
- target.file,
111
- statement.source.value,
112
- [localName, ...rest],
113
- followed,
114
- );
115
- }
116
- for (const declaration of parsed.module.staticImports) {
117
- const binding = declaration.entries.find(
118
- (entry) => !entry.isType && entry.localName.value === localName,
119
- );
120
- if (binding !== undefined) {
121
- const importedMembers =
122
- binding.importName.kind === "NamespaceObject"
123
- ? rest
124
- : [binding.importName.name ?? "", ...rest];
125
- return yield* taskExportFrom(
126
- target.file,
127
- declaration.moduleRequest.value,
128
- importedMembers,
129
- followed,
130
- );
131
- }
132
- }
133
- }
134
- }
135
- const isValueStarExport =
136
- statement.type === "ExportAllDeclaration" && statement.exportKind !== "type";
137
- if (isValueStarExport) {
138
- const exported =
139
- statement.exported === null ? undefined : exportNameOf(statement.exported);
140
- const forwardsName = exported === undefined || exported === name;
141
- if (forwardsName) {
142
- const found = yield* taskExportFrom(
143
- target.file,
144
- statement.source.value,
145
- exported === undefined ? members : rest,
146
- followed,
147
- );
148
- if (found !== undefined) {
149
- return found;
150
- }
151
- }
152
- }
153
- }
154
- return yield* Effect.undefined;
155
- });
156
- const imports = new Map<string, readonly string[]>();
157
- const parsed = parseSync(file, text);
158
- const candidates = candidateImportRoots(parsed);
159
- for (const declaration of parsed.module.staticImports) {
160
- for (const entry of declaration.entries) {
161
- const isCandidate = !entry.isType && candidates.has(entry.localName.value);
162
- if (!isCandidate) {
163
- continue;
164
- }
165
- const members =
166
- entry.importName.kind === "NamespaceObject" ? [] : [entry.importName.name ?? ""];
167
- const reference = yield* taskExportFrom(file, declaration.moduleRequest.value, members);
168
- if (reference !== undefined) {
169
- imports.set(entry.localName.value, reference);
170
- }
171
- }
172
- }
173
- return imports;
174
- });
175
-
176
- export const isTaskLayoutFile = (file: string) =>
177
- isScript(file) &&
178
- (isTopLevelScript(file) || (directoryOf(file) === "" && !isRootSupportFile(file)));