Open History to see the last commit
1import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "./pairingUrl";
2
3const DEFAULT_HOSTED_APP_URL = "https://app.t3.codes";
4
5export interface HostedPairingRequest {
6 readonly host: string;
7 readonly token: string;
8 readonly label: string;
9}
10
11function configuredHostedAppUrl(): string {
12 return import.meta.env.VITE_HOSTED_APP_URL?.trim() || DEFAULT_HOSTED_APP_URL;
13}
14
15function configuredBackendUrl(): string {
16 return import.meta.env.VITE_HTTP_URL?.trim() || import.meta.env.VITE_WS_URL?.trim() || "";
17}
18
19function originFromUrl(value: string): string | null {
20 try {
21 return new URL(value).origin;
22 } catch {
23 return null;
24 }
25}
26
27export function isHostedStaticApp(url: URL = new URL(window.location.href)): boolean {
28 if (configuredBackendUrl()) {
29 return false;
30 }
31
32 const hostedOrigin = originFromUrl(configuredHostedAppUrl());
33 return hostedOrigin !== null && url.origin === hostedOrigin;
34}
35
36export function readHostedPairingRequest(url: URL = new URL(window.location.href)) {
37 const host = url.searchParams.get("host")?.trim() ?? "";
38 const token = getPairingTokenFromUrl(url)?.trim() ?? "";
39 const label = url.searchParams.get("label")?.trim() ?? "";
40
41 if (!host || !token) {
42 return null;
43 }
44
45 return {
46 host,
47 token,
48 label,
49 } satisfies HostedPairingRequest;
50}
51
52export function hasHostedPairingRequest(url: URL = new URL(window.location.href)): boolean {
53 return readHostedPairingRequest(url) !== null;
54}
55
56export function buildHostedPairingUrl(input: {
57 readonly host: string;
58 readonly token: string;
59 readonly label?: string | null;
60}): string {
61 const url = new URL("/pair", configuredHostedAppUrl());
62 url.searchParams.set("host", input.host);
63
64 const label = input.label?.trim();
65 if (label) {
66 url.searchParams.set("label", label);
67 }
68
69 return setPairingTokenOnUrl(url, input.token).toString();
70}