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

desktopSshHosts.ts

77 lines2.5 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​
54export function createDesktopSshHostsStateAtom(
55 getBridge: () => DesktopSshDiscoveryBridge | undefined,
56) {
57 const discoverDesktopSshHosts = Effect.fn("discoverDesktopSshHosts")(function* () {
58 const bridge = getBridge();
59 if (!bridge) {
60 return yield* new DesktopSshDiscoveryUnavailableError();
61 }
62 return yield* Effect.tryPromise({
63 try: (): Promise<ReadonlyArray<DesktopDiscoveredSshHost>> => bridge.discoverSshHosts(),
64 catch: (cause) => new DesktopSshDiscoveryError({ cause }),
65 });
66 });
67​
68 return Atom.make(discoverDesktopSshHosts()).pipe(
69 Atom.swr({ staleTime: 30_000, revalidateOnMount: true }),
70 Atom.keepAlive,
71 Atom.withLabel("desktop:ssh-hosts"),
72 );
74​
75export const desktopSshHostsStateAtom = createDesktopSshHostsStateAtom(
76 getDesktopSshDiscoveryBridge,
77);