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

ElectronShell.ts

68 lines2.1 KB

1import { REMOTE_CAPABLE_EDITOR_IDS, remoteSchemeForEditor } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6​
7import * as Electron from "electron";
8​
9// Remote open-in-editor deep links (`vscode://vscode-remote/ssh-remote+…`)
10// must reach the OS handler; every other non-web scheme stays blocked.
11const SAFE_WEB_PROTOCOLS = new Set(["http:", "https:"]);
12const REMOTE_EDITOR_PROTOCOLS = new Set(
13 REMOTE_CAPABLE_EDITOR_IDS.flatMap((id) => {
14 const scheme = remoteSchemeForEditor(id);
15 return scheme === undefined ? [] : [`${scheme}:`];
16 }),
17);
18​
19const isRemoteEditorUrl = (url: URL) =>
20 REMOTE_EDITOR_PROTOCOLS.has(url.protocol) &&
21 url.username.length === 0 &&
22 url.password.length === 0 &&
23 url.host === "vscode-remote" &&
24 url.pathname.startsWith("/ssh-remote+") &&
25 url.pathname.length > "/ssh-remote+".length;
26​
27export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
28 if (typeof rawUrl !== "string") {
29 return Option.none();
30 }
31​
32 try {
33 const url = new URL(rawUrl);
34 return SAFE_WEB_PROTOCOLS.has(url.protocol) || isRemoteEditorUrl(url)
35 ? Option.some(url.href)
36 : Option.none();
37 } catch {
38 return Option.none();
39 }
41​
42export class ElectronShell extends Context.Service<
43 ElectronShell,
44 {
45 readonly openExternal: (rawUrl: unknown) => Effect.Effect<boolean>;
46 readonly copyText: (text: string) => Effect.Effect<void>;
47 }
48>()("@t3tools/desktop/electron/ElectronShell") {}
49​
50export const make = ElectronShell.of({
51 openExternal: (rawUrl) =>
52 Option.match(parseSafeExternalUrl(rawUrl), {
53 onNone: () => Effect.succeed(false),
54 onSome: (externalUrl) =>
55 Effect.promise(() =>
56 Electron.shell.openExternal(externalUrl).then(
57 () => true,
58 () => false,
59 ),
60 ),
61 }),
62 copyText: (text) =>
63 Effect.sync(() => {
64 Electron.clipboard.writeText(text);
65 }),
66});
67​
68export const layer = Layer.succeed(ElectronShell, make);