Open History to see the last commit
1import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
2
3import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "./pairingUrl";
4
5export interface HostedPairingRequest {
6 readonly host: string;
7 readonly token: string;
8 readonly label: string;
9}
10
11export type HostedAppChannel = "latest" | "nightly";
12
13export function configuredHostedAppUrl(): string {
14 return import.meta.env.VITE_HOSTED_APP_URL?.trim() || DEFAULT_HOSTED_APP_URL;
15}
16
17function configuredBackendUrl(): string {
18 return import.meta.env.VITE_HTTP_URL?.trim() || import.meta.env.VITE_WS_URL?.trim() || "";
19}
20
21function configuredHostedAppChannel(): HostedAppChannel | null {
22 const channel = import.meta.env.VITE_HOSTED_APP_CHANNEL?.trim().toLowerCase();
23 return channel === "latest" || channel === "nightly" ? channel : null;
24}
25
26function originFromUrl(value: string): string | null {
27 try {
28 return new URL(value).origin;
29 } catch {
30 return null;
31 }
32}
33
34export function isHostedStaticApp(url?: URL): boolean {
35 if (configuredBackendUrl()) {
36 return false;
37 }
38
39 if (configuredHostedAppChannel()) {
40 return true;
41 }
42
43 // No window (tests, static render) means no origin to be hosted at.
44 if (url === undefined && typeof window === "undefined") {
45 return false;
46 }
47
48 const hostedOrigin = originFromUrl(configuredHostedAppUrl());
49 return hostedOrigin !== null && (url ?? new URL(window.location.href)).origin === hostedOrigin;
50}
51
52export function readHostedPairingRequest(url: URL = new URL(window.location.href)) {
53 const host = url.searchParams.get("host")?.trim() ?? "";
54 const token = getPairingTokenFromUrl(url)?.trim() ?? "";
55 const label = url.searchParams.get("label")?.trim() ?? "";
56
57 if (!host || !token) {
58 return null;
59 }
60
61 return {
62 host,
63 token,
64 label,
65 } satisfies HostedPairingRequest;
66}
67
68export function hasHostedPairingRequest(url: URL = new URL(window.location.href)): boolean {
69 return readHostedPairingRequest(url) !== null;
70}
71
72export function buildHostedPairingUrl(input: {
73 readonly host: string;
74 readonly token: string;
75 readonly label?: string | null;
76}): string {
77 const url = new URL("/pair", configuredHostedAppUrl());
78 url.searchParams.set("host", input.host);
79
80 const label = input.label?.trim();
81 if (label) {
82 url.searchParams.set("label", label);
83 }
84
85 return setPairingTokenOnUrl(url, input.token).toString();
86}
87
88export function buildHostedChannelSelectionUrl(input: {
89 readonly channel: HostedAppChannel;
90}): string {
91 const url = new URL("/__t3code/channel", configuredHostedAppUrl());
92 url.searchParams.set("channel", input.channel);
93 return url.toString();
94}