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

connection.ts

78 lines2.2 KB

1import { type AuthClientPresentationMetadata, EnvironmentId } from "@t3tools/contracts";
2import {
3 bootstrapRemoteBearerSession,
4 fetchRemoteEnvironmentDescriptor,
5} from "@t3tools/client-runtime";
6import { resolveRemotePairingTarget, stripPairingTokenFromUrl } from "@t3tools/shared/remote";
7import { Platform } from "react-native";
8import { mobileRemoteHttpRuntime } from "./runtime";
9​
10export interface RemoteConnectionInput {
11 readonly pairingUrl: string;
13​
14export interface SavedRemoteConnection {
15 readonly environmentId: EnvironmentId;
16 readonly environmentLabel: string;
17 readonly pairingUrl: string;
18 readonly displayUrl: string;
19 readonly httpBaseUrl: string;
20 readonly wsBaseUrl: string;
21 readonly bearerToken: string;
23​
24export type RemoteClientConnectionState =
25 | "idle"
26 | "connecting"
27 | "ready"
28 | "reconnecting"
29 | "disconnected";
30​
31export function redactPairingCredential(pairingUrl: string): string {
32 const trimmed = pairingUrl.trim();
33 try {
34 return stripPairingTokenFromUrl(new URL(trimmed)).toString();
35 } catch {
36 return trimmed;
37 }
39​
40export function mobileAuthClientMetadata(): AuthClientPresentationMetadata {
41 return {
42 label: "T3 Code Mobile",
43 deviceType: "mobile",
44 ...(Platform.OS === "ios" ? { os: "iOS" } : Platform.OS === "android" ? { os: "Android" } : {}),
45 };
47​
48export async function bootstrapRemoteConnection(
49 input: RemoteConnectionInput,
50): Promise<SavedRemoteConnection> {
51 const target = resolveRemotePairingTarget({
52 pairingUrl: input.pairingUrl,
53 });
54​
55 const descriptor = await mobileRemoteHttpRuntime.runPromise(
56 fetchRemoteEnvironmentDescriptor({
57 httpBaseUrl: target.httpBaseUrl,
58 }),
59 );
60​
61 const bootstrap = await mobileRemoteHttpRuntime.runPromise(
62 bootstrapRemoteBearerSession({
63 httpBaseUrl: target.httpBaseUrl,
64 credential: target.credential,
65 clientMetadata: mobileAuthClientMetadata(),
66 }),
67 );
68​
69 return {
70 environmentId: descriptor.environmentId,
71 environmentLabel: descriptor.label,
72 pairingUrl: redactPairingCredential(input.pairingUrl),
73 displayUrl: target.httpBaseUrl,
74 httpBaseUrl: target.httpBaseUrl,
75 wsBaseUrl: target.wsBaseUrl,
76 bearerToken: bootstrap.access_token,
77 };