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

DesktopClerk.test.ts

245 lines8.5 KB

1import * as NodePath from "@effect/platform-node/NodePath";
2import { assert, describe, it } from "@effect/vitest";
3import * as Cause from "effect/Cause";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import { beforeEach, vi } from "vite-plus/test";
7​
8const { createClerkBridgeMock, storageAdapter, storageMock } = vi.hoisted(() => ({
9 createClerkBridgeMock: vi.fn(),
10 storageAdapter: {
11 getItem: vi.fn(),
12 setItem: vi.fn(),
13 removeItem: vi.fn(),
14 },
15 storageMock: vi.fn(),
16}));
17​
18vi.mock("@clerk/electron", () => ({
19 createClerkBridge: createClerkBridgeMock,
20}));
21​
22vi.mock("@clerk/electron/storage", () => ({
23 storage: storageMock,
24}));
25​
26import * as Exit from "effect/Exit";
27import * as FileSystem from "effect/FileSystem";
28import * as ElectronApp from "../electron/ElectronApp.ts";
29import * as ElectronWindow from "../electron/ElectronWindow.ts";
30import * as DesktopClerk from "./DesktopClerk.ts";
31import * as DesktopEnvironment from "./DesktopEnvironment.ts";
32import * as DesktopPreReadyFileSystem from "./DesktopPreReadyFileSystem.ts";
33​
34const makeDesktopClerkLayer = (
35 isDevelopment = true,
36 events: string[] = [],
37 platform: NodeJS.Platform = "darwin",
38 fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = FileSystem.layerNoop({
39 exists: () => Effect.succeed(false),
40 }),
41) => {
42 const environment = DesktopEnvironment.DesktopEnvironment.of({
43 stateDir: "/tmp/t3-state",
44 isDevelopment,
45 appDataDirectory: "/tmp/app-data",
46 platform,
47 } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
48​
49 const electronApp = {
50 setPath: (name: string, value: string) =>
51 Effect.sync(() => {
52 events.push(`setPath:${name}:${value}`);
53 }),
54 } as unknown as ElectronApp.ElectronApp["Service"];
55​
56 return DesktopClerk.layer.pipe(
57 Layer.provide(
58 Layer.mergeAll(
59 NodePath.layerPosix,
60 Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment),
61 Layer.succeed(ElectronApp.ElectronApp, electronApp),
62 fileSystemLayer,
63 ),
64 ),
65 );
66};
67​
68describe("DesktopClerk", () => {
69 beforeEach(() => {
70 createClerkBridgeMock.mockReset();
71 storageMock.mockReset();
72 });
73​
74 it.effect("acquires and releases the SDK bridge with the layer", () => {
75 const cleanup = vi.fn();
76 const events: string[] = [];
77 storageMock.mockReturnValue(storageAdapter);
78 createClerkBridgeMock.mockImplementation(() => {
79 events.push("createClerkBridge");
80 return { cleanup, isPrimaryInstance: true };
81 });
82​
83 return Effect.gen(function* () {
84 yield* Effect.scoped(Layer.build(makeDesktopClerkLayer(true, events)));
85​
86 assert.deepEqual(createClerkBridgeMock.mock.calls, [
87 [
88 {
89 storage: storageAdapter,
90 passkeys: true,
91 renderer: { scheme: "t3code-dev", host: "app" },
92 },
93 ],
94 ]);
95 assert.equal(cleanup.mock.calls.length, 1);
96 // The bridge acquires Electron's single-instance lock at creation, and
97 // the lock both lives in and creates the userData directory — so the
98 // real path must be set before the bridge exists.
99 assert.deepEqual(events, ["setPath:userData:/tmp/app-data/t3code-dev", "createClerkBridge"]);
100 storageMock.mockClear();
101 createClerkBridgeMock.mockClear();
102 });
103 });
104​
105 it.each([
106 {
107 name: "packaged Windows",
108 isDevelopment: false,
109 platform: "win32" as const,
110 userData: "/tmp/app-data/t3code-v2",
111 },
112 {
113 name: "development",
114 isDevelopment: true,
115 platform: "win32" as const,
116 userData: "/tmp/app-data/t3code-dev",
117 },
118 ])(
119 "creates the bridge before startup can yield to the event loop ($name)",
120 ({ isDevelopment, platform, userData }) => {
121 const events: string[] = [];
122 storageMock.mockReturnValue(storageAdapter);
123 createClerkBridgeMock.mockImplementation(() => {
124 events.push("createClerkBridge");
125 return { cleanup: vi.fn(), isPrimaryInstance: true };
126 });
127 // runSync throws if the layer ever suspends, which would let Electron emit
128 // ready before the bridge exists. main.ts provides the same FileSystem.
129 // oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- The assertion IS that the layer builds synchronously; it.effect would mask a regression to async.
130 Effect.runSync(
131 Effect.scoped(
132 Layer.build(
133 makeDesktopClerkLayer(isDevelopment, events, platform, DesktopPreReadyFileSystem.layer),
134 ),
135 ),
136 );
137​
138 assert.deepEqual(events, [`setPath:userData:${userData}`, "createClerkBridge"]);
139 },
140 );
141​
142 it.effect("preserves bridge initialization failures", () => {
143 const cause = new Error("bridge initialization failed");
144 storageMock.mockReturnValue(storageAdapter);
145 createClerkBridgeMock.mockImplementationOnce(() => {
146 throw cause;
147 });
148​
149 return Effect.gen(function* () {
150 const error = yield* Effect.scoped(Layer.build(makeDesktopClerkLayer())).pipe(Effect.flip);
151​
152 assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeInitializationError);
153 assert.equal(error.stateDir, "/tmp/t3-state");
154 assert.equal(error.isDevelopment, true);
155 assert.strictEqual(error.cause, cause);
156 assert.equal(
157 error.message,
158 'Failed to initialize the desktop Clerk bridge for state directory "/tmp/t3-state" (development: true).',
159 );
160 });
161 });
162​
163 it.effect("preserves bridge cleanup failures", () => {
164 const cause = new Error("bridge cleanup failed");
165 storageMock.mockReturnValue(storageAdapter);
166 createClerkBridgeMock.mockReturnValue({
167 cleanup: () => {
168 throw cause;
169 },
170 });
171​
172 return Effect.gen(function* () {
173 const exit = yield* Effect.exit(Effect.scoped(Layer.build(makeDesktopClerkLayer(false))));
174​
175 assert.equal(exit._tag, "Failure");
176 if (exit._tag === "Failure") {
177 const error = Cause.squash(exit.cause);
178 assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeCleanupError);
179 assert.equal(error.stateDir, "/tmp/t3-state");
180 assert.equal(error.isDevelopment, false);
181 assert.strictEqual(error.cause, cause);
182 assert.equal(
183 error.message,
184 'Failed to clean up the desktop Clerk bridge for state directory "/tmp/t3-state" (development: false).',
185 );
186 }
187 });
188 });
189​
190 it.effect("registers the second-instance handler in the primary instance", () => {
191 storageMock.mockReturnValue(storageAdapter);
192 createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: true });
193 const quit = vi.fn();
194 const registeredEvents: string[] = [];
195 const electronApp = {
196 quit: Effect.sync(quit),
197 on: (eventName: string) =>
198 Effect.sync(() => {
199 registeredEvents.push(eventName);
200 }),
201 } as unknown as ElectronApp.ElectronApp["Service"];
202 const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];
203​
204 return Effect.gen(function* () {
205 const clerk = yield* DesktopClerk.DesktopClerk;
206 const exit = yield* Effect.exit(Effect.scoped(clerk.configure));
207​
208 assert.isTrue(Exit.isSuccess(exit));
209 assert.equal(quit.mock.calls.length, 0);
210 assert.deepEqual(registeredEvents, ["second-instance"]);
211 }).pipe(
212 Effect.provide(makeDesktopClerkLayer()),
213 Effect.provideService(ElectronApp.ElectronApp, electronApp),
214 Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
215 );
216 });
217​
218 it.effect("quits and interrupts startup in a secondary instance", () => {
219 storageMock.mockReturnValue(storageAdapter);
220 createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: false });
221 const quit = vi.fn();
222 const registeredEvents: string[] = [];
223 const electronApp = {
224 quit: Effect.sync(quit),
225 on: (eventName: string) =>
226 Effect.sync(() => {
227 registeredEvents.push(eventName);
228 }),
229 } as unknown as ElectronApp.ElectronApp["Service"];
230 const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];
231​
232 return Effect.gen(function* () {
233 const clerk = yield* DesktopClerk.DesktopClerk;
234 const exit = yield* Effect.exit(Effect.scoped(clerk.configure));
235​
236 assert.isTrue(Exit.hasInterrupts(exit));
237 assert.equal(quit.mock.calls.length, 1);
238 assert.deepEqual(registeredEvents, []);
239 }).pipe(
240 Effect.provide(makeDesktopClerkLayer()),
241 Effect.provideService(ElectronApp.ElectronApp, electronApp),
242 Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
243 );
244 });
245});