Fork Horse repository, listed by its owner. Publisher snapshot.

packages/forkhorse-gatekeeper/src/host-connection.ts

Snapshot at 34e3175

Containing directory

1,075 bytes · typescriptView raw
1import type { SidebarUi } from "./ui-types.ts";
2
3/** A closed host port may be replaced; a healthy host never receives a second handshake. */
4export function hostConnection<T extends { readonly ui: PromiseLike<SidebarUi> | SidebarUi }>(
5  connect: () => { host: T; dispose(): void },
6) {
7  let connection = connect();
8  let disposed = false;
9  return {
10    get host() {
11      return connection.host;
12    },
13    async acquireUi(isCurrent: () => boolean = () => true): Promise<SidebarUi> {
14      if (disposed) throw new Error("Host connection closed.");
15      try {
16        return await connection.host.ui;
17      } catch (error) {
18        if (disposed || !isCurrent()) throw error;
19        // The host's local ui getter has no service work: a failed getter means its RPC session
20        // is unavailable. The pinned host resets its handshake when the frame capability changes.
21        connection.dispose();
22        connection = connect();
23        return await connection.host.ui;
24      }
25    },
26    dispose() {
27      disposed = true;
28      connection.dispose();
29    },
30  };
31}
32