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

DesktopClerk.ts

152 lines5.4 KB

1import { createClerkBridge } from "@clerk/electron";
2import { storage } from "@clerk/electron/storage";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Schema from "effect/Schema";
8import * as Scope from "effect/Scope";
9​
10import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
11import * as ElectronApp from "../electron/ElectronApp.ts";
12import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
13import * as ElectronWindow from "../electron/ElectronWindow.ts";
14import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
15import * as DesktopEnvironment from "./DesktopEnvironment.ts";
16​
17declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
18​
19export class DesktopClerkBridgeInitializationError extends Schema.TaggedErrorClass<DesktopClerkBridgeInitializationError>()(
20 "DesktopClerkBridgeInitializationError",
21 {
22 stateDir: Schema.String,
23 isDevelopment: Schema.Boolean,
24 cause: Schema.Defect(),
25 },
26) {
27 override get message(): string {
28 return `Failed to initialize the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
29 }
31​
32export class DesktopClerkBridgeCleanupError extends Schema.TaggedErrorClass<DesktopClerkBridgeCleanupError>()(
33 "DesktopClerkBridgeCleanupError",
34 {
35 stateDir: Schema.String,
36 isDevelopment: Schema.Boolean,
37 cause: Schema.Defect(),
38 },
39) {
40 override get message(): string {
41 return `Failed to clean up the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;
42 }
44​
45export class DesktopClerk extends Context.Service<
46 DesktopClerk,
47 {
48 readonly configure: Effect.Effect<
49 void,
50 never,
51 ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope
52 >;
53 }
54>()("@t3tools/desktop/app/DesktopClerk") {}
55​
56export function resolveDesktopClerkFrontendApiHostname(
57 publishableKey: string | undefined,
58): string | undefined {
59 const normalizedKey = publishableKey?.trim();
60 if (!normalizedKey) return undefined;
61​
62 try {
63 return clerkFrontendApiHostnameFromPublishableKey(normalizedKey);
64 } catch {
65 return undefined;
66 }
68​
69export const desktopClerkFrontendApiHostname = resolveDesktopClerkFrontendApiHostname(
70 typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"
71 ? undefined
72 : __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,
73);
74​
75export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean) {
76 return createClerkBridge({
77 storage: storage({ path: stateDir }),
78 passkeys: true,
79 renderer: {
80 scheme: ElectronProtocol.getDesktopScheme(isDevelopment),
81 host: ElectronProtocol.DESKTOP_HOST,
82 },
83 });
85​
86export const make = Effect.gen(function* () {
87 const environment = yield* DesktopEnvironment.DesktopEnvironment;
88 const electronApp = yield* ElectronApp.ElectronApp;
89​
90 // Electron scopes the single-instance lock to the userData directory and
91 // creates that directory when the lock is acquired. The SDK bridge takes
92 // the lock at creation, so userData must already point at the real
93 // directory here — under the default productName-derived path, acquiring
94 // the lock would create "T3 Code (Alpha)" and make the legacy-install
95 // detection in resolveUserDataPath match on fresh installs.
96 const userDataPath = yield* DesktopAppIdentity.resolveUserDataPath;
97 yield* electronApp.setPath("userData", userDataPath);
98​
99 const bridge = yield* Effect.acquireRelease(
100 Effect.try({
101 try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),
102 catch: (cause) =>
103 new DesktopClerkBridgeInitializationError({
104 stateDir: environment.stateDir,
105 isDevelopment: environment.isDevelopment,
106 cause,
107 }),
108 }),
109 (bridge) =>
110 Effect.try({
111 try: () => bridge.cleanup(),
112 catch: (cause) =>
113 new DesktopClerkBridgeCleanupError({
114 stateDir: environment.stateDir,
115 isDevelopment: environment.isDevelopment,
116 cause,
117 }),
118 }).pipe(Effect.orDie),
119 );
120​
121 return DesktopClerk.of({
122 configure: Effect.gen(function* () {
123 const electronApp = yield* ElectronApp.ElectronApp;
124 const electronWindow = yield* ElectronWindow.ElectronWindow;
125 const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
126 const runPromise = Effect.runPromiseWith(context);
127​
128 // The SDK bridge holds Electron's single-instance lock (acquired at
129 // bridge creation) so OAuth deep-link callbacks on Windows/Linux are
130 // forwarded to the running app. In a secondary instance the bridge has
131 // already begun quitting the app; app.quit() is asynchronous, so stop
132 // bootstrap here before whenReady can fire.
133 if (!bridge.isPrimaryInstance) {
134 yield* electronApp.quit;
135 return yield* Effect.interrupt;
136 }
137​
138 yield* electronApp.on("second-instance", () => {
139 void runPromise(
140 Effect.gen(function* () {
141 const mainWindow = yield* electronWindow.currentMainOrFirst;
142 if (Option.isSome(mainWindow)) {
143 yield* electronWindow.reveal(mainWindow.value);
144 }
145 }),
146 );
147 });
148 }).pipe(Effect.withSpan("desktop.clerk.configure")),
149 });
150});
151​
152export const layer = Layer.effect(DesktopClerk, make);