Open History to see the last commit
1import { getPairingTokenFromUrl } from "../../pairingUrl";
2
3export interface ResolvedRemotePairingTarget {
4 readonly credential: string;
5 readonly httpBaseUrl: string;
6 readonly wsBaseUrl: string;
7}
8
9function normalizeRemoteBaseUrl(rawValue: string): URL {
10 const trimmed = rawValue.trim();
11 if (!trimmed) {
12 throw new Error("Enter a backend URL.");
13 }
14
15 const normalizedInput =
16 /^[a-zA-Z][a-zA-Z\d+-]*:\/\//.test(trimmed) || trimmed.startsWith("//")
17 ? trimmed
18 : `https://${trimmed}`;
19 const url = new URL(normalizedInput, window.location.origin);
20 url.pathname = "/";
21 url.search = "";
22 url.hash = "";
23 return url;
24}
25
26function toHttpBaseUrl(url: URL): string {
27 const next = new URL(url.toString());
28 if (next.protocol === "ws:") {
29 next.protocol = "http:";
30 } else if (next.protocol === "wss:") {
31 next.protocol = "https:";
32 }
33 next.pathname = "/";
34 next.search = "";
35 next.hash = "";
36 return next.toString();
37}
38
39function toWsBaseUrl(url: URL): string {
40 const next = new URL(url.toString());
41 if (next.protocol === "http:") {
42 next.protocol = "ws:";
43 } else if (next.protocol === "https:") {
44 next.protocol = "wss:";
45 }
46 next.pathname = "/";
47 next.search = "";
48 next.hash = "";
49 return next.toString();
50}
51
52export function resolveRemotePairingTarget(input: {
53 readonly pairingUrl?: string;
54 readonly host?: string;
55 readonly pairingCode?: string;
56}): ResolvedRemotePairingTarget {
57 const pairingUrl = input.pairingUrl?.trim() ?? "";
58 if (pairingUrl.length > 0) {
59 const url = new URL(pairingUrl, window.location.origin);
60 const credential = getPairingTokenFromUrl(url) ?? "";
61 if (!credential) {
62 throw new Error("Pairing URL is missing its token.");
63 }
64 return {
65 credential,
66 httpBaseUrl: toHttpBaseUrl(url),
67 wsBaseUrl: toWsBaseUrl(url),
68 };
69 }
70
71 const host = input.host?.trim() ?? "";
72 const pairingCode = input.pairingCode?.trim() ?? "";
73 if (!host) {
74 throw new Error("Enter a backend URL.");
75 }
76 if (!pairingCode) {
77 throw new Error("Enter a pairing code.");
78 }
79
80 const normalizedHost = normalizeRemoteBaseUrl(host);
81 return {
82 credential: pairingCode,
83 httpBaseUrl: toHttpBaseUrl(normalizedHost),
84 wsBaseUrl: toWsBaseUrl(normalizedHost),
85 };
86}