Skip to content
Source
Sign inSign up

desktopSshHosts.ts

75 lines2.4 KB

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 (
22 alias.includes(normalizedQuery) ||
23 host.hostname.toLowerCase().includes(normalizedQuery)
24 ) {
25 substringMatches.push(host);
26 }
27 }
28​
29 return [...prefixMatches, ...substringMatches];
31​
32class DesktopSshDiscoveryUnavailableError extends Schema.TaggedError<DesktopSshDiscoveryUnavailableError>()(
33 "DesktopSshDiscoveryUnavailableError",
34 {},
35) {
36 override get message(): string {
37 return "Desktop SSH host discovery is unavailable.";
38 }
40​
41class DesktopSshDiscoveryError extends Schema.TaggedError<DesktopSshDiscoveryError>()(
42 "DesktopSshDiscoveryError",
43 { cause: Schema.Defect() },
44) {
45 override get message(): string {
46 return "Failed to discover SSH hosts.";
47 }
49​
50function getDesktopSshDiscoveryBridge(): DesktopSshDiscoveryBridge | undefined {
51 return typeof window === "undefined" ? undefined : window.desktopBridge;
53​
54function createDesktopSshHostsStateAtom(getBridge: () => DesktopSshDiscoveryBridge | undefined) {
55 const discoverDesktopSshHosts = Effect.fn("discoverDesktopSshHosts")(function* () {
56 const bridge = getBridge();
57 if (!bridge) {
58 return yield* new DesktopSshDiscoveryUnavailableError();
59 }
60 return yield* Effect.tryPromise({
61 try: (): Promise<ReadonlyArray<DesktopDiscoveredSshHost>> => bridge.discoverSshHosts(),
62 catch: (cause) => new DesktopSshDiscoveryError({ cause }),
63 });
64 });
65​
66 return Atom.make(discoverDesktopSshHosts()).pipe(
67 Atom.swr({ staleTime: 30_000, revalidateOnMount: true }),
68 Atom.keepAlive,
69 Atom.withLabel("desktop:ssh-hosts"),
70 );
72​
73export const desktopSshHostsStateAtom = createDesktopSshHostsStateAtom(
74 getDesktopSshDiscoveryBridge,
75);