Open History to see the last commit
1import type { DesktopBridge, DesktopDiscoveredSshHost } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Schema from "effect/Schema";
4import { Atom } from "effect/reactivity";
5
6type DesktopSshDiscoveryBridge = Pick<DesktopBridge, "discoverSshHosts">;
7
8export function filterDiscoveredSshHosts(
9 hosts: ReadonlyArray<DesktopDiscoveredSshHost>,
10 query: string,
11): ReadonlyArray<DesktopDiscoveredSshHost> {
12 const normalizedQuery = query.trim().toLowerCase();
13 if (normalizedQuery.length === 0) return hosts;
14
15 const prefixMatches: Array<DesktopDiscoveredSshHost> = [];
16 const substringMatches: Array<DesktopDiscoveredSshHost> = [];
17 for (const host of hosts) {
18 const alias = host.alias.toLowerCase();
19 if (alias.startsWith(normalizedQuery)) {
20 prefixMatches.push(host);
21 } else if (alias.includes(normalizedQuery)) {
22 substringMatches.push(host);
23 }
24 }
25
26 return [...prefixMatches, ...substringMatches];
27}
28
29class DesktopSshDiscoveryUnavailableError extends Schema.TaggedError<DesktopSshDiscoveryUnavailableError>()(
30 "DesktopSshDiscoveryUnavailableError",
31 {},
32) {
33 override get message(): string {
34 return "Desktop SSH host discovery is unavailable.";
35 }
36}
37
38class DesktopSshDiscoveryError extends Schema.TaggedError<DesktopSshDiscoveryError>()(
39 "DesktopSshDiscoveryError",
40 { cause: Schema.Defect() },
41) {
42 override get message(): string {
43 return "Failed to discover SSH hosts.";
44 }
45}
46
47function getDesktopSshDiscoveryBridge(): DesktopSshDiscoveryBridge | undefined {
48 return typeof window === "undefined" ? undefined : window.desktopBridge;
49}
50
51export function createDesktopSshHostsStateAtom(
52 getBridge: () => DesktopSshDiscoveryBridge | undefined,
53) {
54 const discoverDesktopSshHosts = Effect.fn("discoverDesktopSshHosts")(function* () {
55 const bridge = getBridge();
56 if (!bridge) {
57 return yield* new DesktopSshDiscoveryUnavailableError();
58 }
59 return yield* Effect.tryPromise({
60 try: (): Promise<ReadonlyArray<DesktopDiscoveredSshHost>> => bridge.discoverSshHosts(),
61 catch: (cause) => new DesktopSshDiscoveryError({ cause }),
62 });
63 });
64
65 return Atom.make(discoverDesktopSshHosts()).pipe(
66 Atom.swr({ staleTime: 30_000, revalidateOnMount: true }),
67 Atom.keepAlive,
68 Atom.withLabel("desktop:ssh-hosts"),
69 );
70}
71
72export const desktopSshHostsStateAtom = createDesktopSshHostsStateAtom(
73 getDesktopSshDiscoveryBridge,
74);