Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

utils.ts

175 lines6.0 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as Data from "effect/Data";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Path from "effect/Path";
7import * as PlatformError from "effect/PlatformError";
8import * as Predicate from "effect/Predicate";
9import * as Schema from "effect/Schema";
10import * as Stream from "effect/Stream";
11import { ChildProcess, ChildProcessSpawner } from "effect/process";
12import * as NodeModule from "node:module";
13​
14// oxlint is only a transitive dependency (via vite-plus), so its bin placement
15// varies by package manager: pnpm hoists it into the virtual store, while
16// other layouts expose vite-plus's LSP-only wrapper instead. Resolve the real
17// package through vite-plus rather than hardcoding either layout, and do it at
18const oxlintPackageJsonPath = NodeModule.createRequire(
19 NodeModule.createRequire(import.meta.url).resolve("vite-plus/package.json"),
20).resolve("oxlint/package.json");
21​
22class OxlintFixtureFailure extends Data.TaggedError("OxlintFixtureFailure")<{
23 readonly exitCode: number;
24 readonly stdout: string;
25 readonly stderr: string;
26}> {
27 static readonly is = (u: unknown): u is OxlintFixtureFailure =>
28 Predicate.isTagged(u, "OxlintFixtureFailure");
30​
31class OxlintFixtureExpectedFailure extends Data.TaggedError("OxlintFixtureExpectedFailure")<{
32 readonly ruleName: string;
33}> {
34 override get message() {
35 return `Expected oxlint to report a failure for rule ${this.ruleName}, but it passed.`;
36 }
38​
39const encodeOxlintConfig = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
40​
41interface RuleHarness {
42 readonly run: (
43 source: string,
44 ) => Effect.Effect<
45 string,
46 OxlintFixtureFailure | PlatformError.PlatformError | Schema.SchemaError,
47 NodeServices.NodeServices
48 >;
49 readonly runAndExpectFailure: (
50 source: string,
51 ) => Effect.Effect<
52 string,
53 OxlintFixtureExpectedFailure | PlatformError.PlatformError | Schema.SchemaError,
54 NodeServices.NodeServices
55 >;
56 readonly valid: (name: string, source: string) => void;
57 readonly invalid: (name: string, source: string, assertion?: (output: string) => void) => void;
59​
60interface RuleHarnessOptions {
61 readonly filename?: string;
62 readonly ruleOptions?: ReadonlyArray<unknown>;
64​
65const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
66 stream.pipe(
67 Stream.decodeText(),
68 Stream.runFold(
69 () => "",
70 (acc, chunk) => acc + chunk,
71 ),
72 );
73​
74const spawnAndCollectOutput = Effect.fnUntraced(function* (command: ChildProcess.Command) {
75 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
76 const child = yield* spawner.spawn(command);
77​
78 const [stdout, stderr, exitCode] = yield* Effect.all(
79 [
80 collectStreamAsString(child.stdout),
81 collectStreamAsString(child.stderr),
82 child.exitCode.pipe(Effect.map(Number)),
83 ],
84 { concurrency: "unbounded" },
85 );
86​
87 return { exitCode, stdout, stderr };
88}, Effect.scoped);
89​
90export const createOxlintRuleHarness = (
91 ruleName: string,
92 options: RuleHarnessOptions = {},
93): RuleHarness => {
94 const [pluginName, shortRuleName] = ruleName.split("/");
95 const diagnosticRuleName =
96 pluginName && shortRuleName ? `${pluginName}\\(${shortRuleName}\\)` : ruleName;
97 const test = it.layer(NodeServices.layer);
98​
99 const run: RuleHarness["run"] = Effect.fnUntraced(function* (source: string) {
100 const fs = yield* FileSystem.FileSystem;
101 const path = yield* Path.Path;
102 const fixtureDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-oxlint-" });
103 const configPath = path.join(fixtureDir, ".oxlintrc.json");
104 const sourcePath = path.join(fixtureDir, options.filename ?? "fixture.ts");
105 const repoRoot = path.join(import.meta.dirname, "..", "..");
106 const oxlintBin = path.join(path.dirname(oxlintPackageJsonPath), "bin", "oxlint");
107 const pluginPath = path.join(repoRoot, "oxlint-plugin-t3code", "index.ts");
108​
109 yield* fs.writeFileString(
110 configPath,
111 yield* encodeOxlintConfig({
112 jsPlugins: [{ name: "t3code", specifier: pluginPath }],
113 rules: { [ruleName]: ["error", ...(options.ruleOptions ?? [])] },
114 }),
115 );
116 yield* fs.makeDirectory(path.dirname(sourcePath), { recursive: true });
117 yield* fs.writeFileString(sourcePath, source);
118​
119 // Run through the current Node binary: oxlint's bin is an extensionless
120 // shebang script, which Windows cannot spawn directly and which would
121 // otherwise pick up whatever node is first on PATH.
122 const output = yield* spawnAndCollectOutput(
123 ChildProcess.make(process.execPath, [oxlintBin, "--config", configPath, sourcePath], {
124 cwd: repoRoot,
125 }),
126 );
127​
128 if (output.exitCode !== 0) {
129 return yield* new OxlintFixtureFailure({
130 exitCode: output.exitCode,
131 stdout: output.stdout,
132 stderr: output.stderr,
133 });
134 }
135​
136 return `${output.stdout}${output.stderr}`;
137 }, Effect.scoped);
138​
139 const runAndExpectFailure: RuleHarness["runAndExpectFailure"] = (source) =>
140 run(source).pipe(
141 Effect.matchEffect({
142 onFailure: (error) =>
143 OxlintFixtureFailure.is(error)
144 ? Effect.succeed(
145 `oxlint fixture failed with exit code ${error.exitCode}\n${error.stdout}\n${error.stderr}`,
146 )
147 : Effect.fail(error),
148 onSuccess: () => Effect.fail(new OxlintFixtureExpectedFailure({ ruleName })),
149 }),
150 );
151​
152 return {
153 run,
154 runAndExpectFailure,
155 valid(name, source) {
156 test(name, (it) => {
157 it.effect("passes", () => run(source));
158 });
159 },
160 invalid(name, source, assertion) {
161 test(name, (it) => {
162 it.effect("reports the rule diagnostic", () =>
163 runAndExpectFailure(source).pipe(
164 Effect.tap((output) =>
165 Effect.sync(() => {
166 assert.match(output, new RegExp(diagnosticRuleName));
167 assertion?.(output);
168 }),
169 ),
170 ),
171 );
172 });
173 },
174 };
175};