Open History to see the last commit
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/unstable/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
18// module scope so a broken install fails once with a resolution error instead
19// of as an opaque defect in every test.
20const oxlintPackageJsonPath = NodeModule.createRequire(
21 NodeModule.createRequire(import.meta.url).resolve("vite-plus/package.json"),
22).resolve("oxlint/package.json");
23
24class OxlintFixtureFailure extends Data.TaggedError("OxlintFixtureFailure")<{
25 readonly exitCode: number;
26 readonly stdout: string;
27 readonly stderr: string;
28}> {
29 static readonly is = (u: unknown): u is OxlintFixtureFailure =>
30 Predicate.isTagged(u, "OxlintFixtureFailure");
31}
32
33class OxlintFixtureExpectedFailure extends Data.TaggedError("OxlintFixtureExpectedFailure")<{
34 readonly ruleName: string;
35}> {
36 override get message() {
37 return `Expected oxlint to report a failure for rule ${this.ruleName}, but it passed.`;
38 }
39}
40
41const encodeOxlintConfig = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
42
43interface RuleHarness {
44 readonly run: (
45 source: string,
46 ) => Effect.Effect<
47 string,
48 OxlintFixtureFailure | PlatformError.PlatformError | Schema.SchemaError,
49 NodeServices.NodeServices
50 >;
51 readonly runAndExpectFailure: (
52 source: string,
53 ) => Effect.Effect<
54 string,
55 OxlintFixtureExpectedFailure | PlatformError.PlatformError | Schema.SchemaError,
56 NodeServices.NodeServices
57 >;
58 readonly valid: (name: string, source: string) => void;
59 readonly invalid: (name: string, source: string, assertion?: (output: string) => void) => void;
60}
61
62interface RuleHarnessOptions {
63 readonly filename?: string;
64}
65
66const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
67 stream.pipe(
68 Stream.decodeText(),
69 Stream.runFold(
70 () => "",
71 (acc, chunk) => acc + chunk,
72 ),
73 );
74
75const spawnAndCollectOutput = Effect.fnUntraced(function* (command: ChildProcess.Command) {
76 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
77 const child = yield* spawner.spawn(command);
78
79 const [stdout, stderr, exitCode] = yield* Effect.all(
80 [
81 collectStreamAsString(child.stdout),
82 collectStreamAsString(child.stderr),
83 child.exitCode.pipe(Effect.map(Number)),
84 ],
85 { concurrency: "unbounded" },
86 );
87
88 return { exitCode, stdout, stderr };
89}, Effect.scoped);
90
91export const createOxlintRuleHarness = (
92 ruleName: string,
93 options: RuleHarnessOptions = {},
94): RuleHarness => {
95 const [pluginName, shortRuleName] = ruleName.split("/");
96 const diagnosticRuleName =
97 pluginName && shortRuleName ? `${pluginName}\\(${shortRuleName}\\)` : ruleName;
98 const test = it.layer(NodeServices.layer);
99
100 const run: RuleHarness["run"] = Effect.fnUntraced(function* (source: string) {
101 const fs = yield* FileSystem.FileSystem;
102 const path = yield* Path.Path;
103 const fixtureDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-oxlint-" });
104 const configPath = path.join(fixtureDir, ".oxlintrc.json");
105 const sourcePath = path.join(fixtureDir, options.filename ?? "fixture.ts");
106 const repoRoot = path.join(import.meta.dirname, "..", "..");
107 const oxlintBin = path.join(path.dirname(oxlintPackageJsonPath), "bin", "oxlint");
108 const pluginPath = path.join(repoRoot, "oxlint-plugin-t3code", "index.ts");
109
110 yield* fs.writeFileString(
111 configPath,
112 yield* encodeOxlintConfig({
113 jsPlugins: [{ name: "t3code", specifier: pluginPath }],
114 rules: { [ruleName]: "error" },
115 }),
116 );
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};