Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as Deferred from "effect/Deferred";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Fiber from "effect/Fiber";
7import * as Path from "effect/Path";
8import * as PlatformError from "effect/PlatformError";
9import * as Schema from "effect/Schema";
10import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
11
12import * as ProcessRunner from "../processRunner.ts";
13import {
14 ensurePinnedRuntimeInstalled,
15 pinnedRuntimePaths,
16 PinnedRuntimeInstallError,
17} from "./pinnedRuntime.ts";
18
19const decodeManifest = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
20
21const successfulRunner = (fs: FileSystem.FileSystem, path: Path.Path) =>
22 ProcessRunner.ProcessRunner.of({
23 run: (input) =>
24 Effect.gen(function* () {
25 if (input.args[0] === "--input-type=commonjs") {
26 return {
27 stdout: "",
28 stderr: "",
29 code: ChildProcessSpawner.ExitCode(0),
30 timedOut: false,
31 stdoutTruncated: false,
32 stderrTruncated: false,
33 stdoutInvalidUtf8: false,
34 stderrInvalidUtf8: false,
35 };
36 }
37 const prefixIndex = input.args.indexOf("--prefix");
38 const stagingDir = input.args[prefixIndex + 1];
39 if (stagingDir === undefined) return yield* Effect.die("missing npm --prefix");
40 assert.deepEqual(
41 yield* decodeManifest(
42 yield* fs.readFileString(path.join(stagingDir, "package.json")).pipe(Effect.orDie),
43 ).pipe(Effect.orDie),
44 { private: true, allowScripts: { "node-pty": true, "msgpackr-extract": true } },
45 );
46 const entry = path.join(stagingDir, "node_modules", "t3", "dist", "bin.mjs");
47 yield* fs.makeDirectory(path.dirname(entry), { recursive: true }).pipe(Effect.orDie);
48 yield* fs.writeFileString(entry, "export {};\n").pipe(Effect.orDie);
49 return {
50 stdout: "",
51 stderr: "",
52 code: ChildProcessSpawner.ExitCode(0),
53 timedOut: false,
54 stdoutTruncated: false,
55 stderrTruncated: false,
56 stdoutInvalidUtf8: false,
57 stderrInvalidUtf8: false,
58 };
59 }),
60 });
61
62it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
63 for (const nativeModuleAvailable of [true, false]) {
64 it.effect(
65 nativeModuleAvailable
66 ? "loads node-pty from the candidate before publishing it"
67 : "rejects a successful install with a missing node-pty native binary",
68 () =>
69 Effect.gen(function* () {
70 const fs = yield* FileSystem.FileSystem;
71 const path = yield* Path.Path;
72 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-native-" });
73 const finalPaths = pinnedRuntimePaths(path, baseDir, "1.2.3");
74 const nodeRunner = yield* ProcessRunner.make();
75 const install = successfulRunner(fs, path);
76 let validated = false;
77 const result = yield* ensurePinnedRuntimeInstalled({
78 baseDir,
79 version: "1.2.3",
80 execPath: process.execPath,
81 fs,
82 path,
83 runner: ProcessRunner.ProcessRunner.of({
84 run: (input) =>
85 input.command !== "npm"
86 ? nodeRunner.run(input)
87 : Effect.gen(function* () {
88 const result = yield* install.run(input);
89 const prefix = input.args[input.args.indexOf("--prefix") + 1]!;
90 const moduleDir = path.join(prefix, "node_modules", "node-pty");
91 yield* fs.makeDirectory(moduleDir, { recursive: true }).pipe(Effect.orDie);
92 yield* fs
93 .writeFileString(
94 path.join(moduleDir, "index.js"),
95 nativeModuleAvailable
96 ? "require('node:fs').writeFileSync(__dirname + '/loaded', 'yes');"
97 : "require('./build/Release/pty.node');",
98 )
99 .pipe(Effect.orDie);
100 return result;
101 }),
102 }),
103 validate: (runtime) =>
104 Effect.gen(function* () {
105 validated = true;
106 assert.isFalse(yield* fs.exists(runtime.sentinelPath));
107 assert.isTrue(
108 yield* fs.exists(path.join(runtime.versionDir, "node_modules/node-pty/loaded")),
109 );
110 }).pipe(Effect.orDie),
111 }).pipe(Effect.result);
112
113 assert.equal(validated, nativeModuleAvailable);
114 assert.equal(yield* fs.exists(finalPaths.sentinelPath), nativeModuleAvailable);
115 if (nativeModuleAvailable) {
116 assert.equal(result._tag, "Success");
117 } else {
118 assert.equal(result._tag, "Failure");
119 if (result._tag === "Failure") {
120 assert.instanceOf(result.failure, PinnedRuntimeInstallError);
121 assert.include(result.failure.message, "loading node-pty");
122 }
123 assert.deepEqual(yield* fs.readDirectory(path.dirname(finalPaths.versionDir)), []);
124 }
125 }),
126 );
127 }
128
129 it.effect("installs through pnpm when its Node runtime has no npm executable", () =>
130 Effect.gen(function* () {
131 const fs = yield* FileSystem.FileSystem;
132 const path = yield* Path.Path;
133 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-pnpm-" });
134 const commands: Array<ProcessRunner.ProcessRunInput> = [];
135 const install = successfulRunner(fs, path);
136 const paths = yield* ensurePinnedRuntimeInstalled({
137 baseDir,
138 version: "1.2.3",
139 execPath: process.execPath,
140 fs,
141 path,
142 runner: ProcessRunner.ProcessRunner.of({
143 run: (input) => {
144 commands.push(input);
145 return input.command === "npm"
146 ? Effect.fail(
147 new ProcessRunner.ProcessSpawnError({
148 command: "npm",
149 argumentCount: input.args.length,
150 cause: PlatformError.systemError({
151 _tag: "NotFound",
152 module: "ChildProcess",
153 method: "spawn",
154 }),
155 }),
156 )
157 : install.run(input);
158 },
159 }),
160 validate: (staging) =>
161 fs.exists(staging.entryPath).pipe(
162 Effect.flatMap((exists) => (exists ? Effect.void : Effect.die("missing runtime"))),
163 Effect.orDie,
164 ),
165 });
166 assert.deepEqual(
167 commands.map((command) => command.command),
168 ["npm", "pnpm", process.execPath],
169 );
170 assert.deepEqual(commands[1]!.args, ["--package=npm@11", "dlx", "npm", ...commands[0]!.args]);
171 assert.equal(yield* fs.readFileString(paths.sentinelPath), "1.2.3\n");
172 }),
173 );
174
175 it.effect("does not try a different installer for npm permission failures", () =>
176 Effect.gen(function* () {
177 const fs = yield* FileSystem.FileSystem;
178 const path = yield* Path.Path;
179 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-permission-" });
180 const commands: string[] = [];
181 yield* ensurePinnedRuntimeInstalled({
182 baseDir,
183 version: "1.2.3",
184 execPath: process.execPath,
185 fs,
186 path,
187 runner: ProcessRunner.ProcessRunner.of({
188 run: (input) => {
189 commands.push(input.command);
190 return Effect.fail(
191 new ProcessRunner.ProcessSpawnError({
192 command: input.command,
193 argumentCount: input.args.length,
194 cause: PlatformError.systemError({
195 _tag: "PermissionDenied",
196 module: "ChildProcess",
197 method: "spawn",
198 }),
199 }),
200 );
201 },
202 }),
203 validate: () => Effect.die("must not validate a failed install"),
204 }).pipe(Effect.flip);
205 assert.deepEqual(commands, ["npm"]);
206 }),
207 );
208
209 it.effect("validates a staging tree before atomically publishing it", () =>
210 Effect.gen(function* () {
211 const fs = yield* FileSystem.FileSystem;
212 const path = yield* Path.Path;
213 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
214 const finalPaths = pinnedRuntimePaths(path, baseDir, "1.2.3");
215 let validatedDirectory = "";
216
217 const installed = yield* ensurePinnedRuntimeInstalled({
218 baseDir,
219 version: "1.2.3",
220 execPath: process.execPath,
221 fs,
222 path,
223 runner: successfulRunner(fs, path),
224 validate: (staging) =>
225 Effect.gen(function* () {
226 validatedDirectory = staging.versionDir;
227 assert.isFalse(yield* fs.exists(finalPaths.versionDir));
228 assert.isTrue(yield* fs.exists(staging.entryPath));
229 }).pipe(Effect.orDie),
230 });
231
232 assert.notEqual(validatedDirectory, finalPaths.versionDir);
233 assert.deepEqual(installed, finalPaths);
234 assert.isTrue(yield* fs.exists(finalPaths.entryPath));
235 assert.equal(yield* fs.readFileString(finalPaths.sentinelPath), "1.2.3\n");
236 }),
237 );
238
239 it.effect("removes staging and leaves no final runtime when validation fails", () =>
240 Effect.gen(function* () {
241 const fs = yield* FileSystem.FileSystem;
242 const path = yield* Path.Path;
243 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
244 const finalPaths = pinnedRuntimePaths(path, baseDir, "1.2.3");
245
246 yield* ensurePinnedRuntimeInstalled({
247 baseDir,
248 version: "1.2.3",
249 execPath: process.execPath,
250 fs,
251 path,
252 runner: successfulRunner(fs, path),
253 validate: () =>
254 Effect.fail(new PinnedRuntimeInstallError({ step: "validating the staged runtime" })),
255 }).pipe(Effect.flip);
256
257 assert.isFalse(yield* fs.exists(finalPaths.versionDir));
258 assert.deepEqual(
259 (yield* fs.readDirectory(path.dirname(finalPaths.versionDir))).filter((entry) =>
260 entry.startsWith(".staging-"),
261 ),
262 [],
263 );
264 }),
265 );
266
267 it.effect("replaces an incomplete pinned runtime", () =>
268 Effect.gen(function* () {
269 const fs = yield* FileSystem.FileSystem;
270 const path = yield* Path.Path;
271 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-repair-" });
272 const finalPaths = pinnedRuntimePaths(path, baseDir, "1.2.3");
273 yield* fs.makeDirectory(finalPaths.versionDir, { recursive: true });
274 yield* fs.writeFileString(path.join(finalPaths.versionDir, "partial"), "incomplete\n");
275
276 yield* ensurePinnedRuntimeInstalled({
277 baseDir,
278 version: "1.2.3",
279 execPath: process.execPath,
280 fs,
281 path,
282 runner: successfulRunner(fs, path),
283 validate: () => Effect.void,
284 });
285
286 assert.isFalse(yield* fs.exists(path.join(finalPaths.versionDir, "partial")));
287 assert.isTrue(yield* fs.exists(finalPaths.entryPath));
288 }),
289 );
290
291 it.effect("preserves a completed runtime when validation fails", () =>
292 Effect.gen(function* () {
293 const fs = yield* FileSystem.FileSystem;
294 const path = yield* Path.Path;
295 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-repair-" });
296 const finalPaths = pinnedRuntimePaths(path, baseDir, "1.2.3");
297 yield* fs.makeDirectory(path.dirname(finalPaths.entryPath), { recursive: true });
298 yield* fs.writeFileString(finalPaths.entryPath, "broken\n");
299 yield* fs.writeFileString(finalPaths.sentinelPath, "1.2.3\n");
300
301 let validations = 0;
302 yield* ensurePinnedRuntimeInstalled({
303 baseDir,
304 version: "1.2.3",
305 execPath: process.execPath,
306 fs,
307 path,
308 runner: successfulRunner(fs, path),
309 validate: (paths) =>
310 Effect.gen(function* () {
311 validations += 1;
312 const source = yield* fs.readFileString(paths.entryPath).pipe(Effect.orDie);
313 if (source === "broken\n") {
314 return yield* new PinnedRuntimeInstallError({ step: "validating the runtime" });
315 }
316 }),
317 }).pipe(Effect.flip);
318
319 assert.equal(validations, 1);
320 assert.equal(yield* fs.readFileString(finalPaths.entryPath), "broken\n");
321 }),
322 );
323
324 it.effect("removes staging when installation is interrupted", () =>
325 Effect.gen(function* () {
326 const fs = yield* FileSystem.FileSystem;
327 const path = yield* Path.Path;
328 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-interrupt-" });
329 const started = yield* Deferred.make<void>();
330 const runner = ProcessRunner.ProcessRunner.of({
331 run: () => Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)),
332 });
333 const install = yield* ensurePinnedRuntimeInstalled({
334 baseDir,
335 version: "1.2.3",
336 execPath: process.execPath,
337 fs,
338 path,
339 runner,
340 validate: () => Effect.void,
341 }).pipe(Effect.forkScoped);
342
343 yield* Deferred.await(started);
344 yield* Fiber.interrupt(install);
345 const versionsDir = path.join(baseDir, "runtime", "versions");
346 assert.deepEqual(yield* fs.readDirectory(versionsDir), []);
347 }),
348 );
349});