Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import { vi } from "vite-plus/test";
5
6import * as CursorSdk from "./CursorSdk.ts";
7
8// Shaped like the SDK's minified class: the constructor is not named after the error.
9// @effect-diagnostics-next-line extendsNativeError:off - mimics the Cursor SDK's own native Error class.
10class o extends Error {
11 override name = "WriteIterableClosedError";
12}
13
14// Calls the guard directly, with Vitest's own listener detached so the guard does not defer to it.
15const rejectThroughGuard = (reason: unknown) =>
16 Effect.gen(function* () {
17 const others = process.listeners("unhandledRejection");
18 yield* Layer.build(CursorSdk.layer);
19 const guard = process.listeners("unhandledRejection").find((l) => !others.includes(l));
20 assert.isDefined(guard);
21 using exit = vi.spyOn(process, "exit").mockImplementation(() => undefined as never);
22 using _log = vi.spyOn(console, "error").mockImplementation(() => {});
23 for (const listener of others) process.off("unhandledRejection", listener);
24 try {
25 guard(reason, Promise.resolve());
26 } finally {
27 for (const listener of others) process.on("unhandledRejection", listener);
28 }
29 return exit.mock.calls;
30 }).pipe(Effect.scoped);
31
32describe("CursorSdk unhandled rejection guard", () => {
33 it.effect("keeps the server running when the SDK writes to a closed stream", () =>
34 Effect.gen(function* () {
35 assert.deepStrictEqual(yield* rejectThroughGuard(new o("WritableIterable is closed")), []);
36 }),
37 );
38
39 it.effect("keeps the server running when the SDK writes after its request stream ended", () =>
40 Effect.gen(function* () {
41 // Shaped like `ConnectError.from(e, Code.Aborted)` from the SDK's connect-node body pump.
42 const cause = Object.assign(new Error("write after end"), {
43 code: "ERR_STREAM_WRITE_AFTER_END",
44 });
45 const reason = Object.assign(new Error("[aborted] write after end", { cause }), {
46 name: "ConnectError",
47 code: 10,
48 rawMessage: "write after end",
49 });
50 assert.deepStrictEqual(yield* rejectThroughGuard(reason), []);
51 }),
52 );
53
54 it.effect("still exits on other rejections", () =>
55 Effect.gen(function* () {
56 assert.deepStrictEqual(yield* rejectThroughGuard(new Error("WritableIterable is closed")), [
57 [1],
58 ]);
59 }),
60 );
61
62 it.effect("still exits on aborted requests other than a write after end", () =>
63 Effect.gen(function* () {
64 const cause = Object.assign(new Error("socket hang up"), { code: "ECONNRESET" });
65 const reason = Object.assign(new Error("[aborted] socket hang up", { cause }), {
66 name: "ConnectError",
67 code: 10,
68 });
69 assert.deepStrictEqual(yield* rejectThroughGuard(reason), [[1]]);
70 }),
71 );
72});