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

hostedPairing.ts

95 lines2.6 KB

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​
13function configuredHostedAppUrl(): string {
14 return import.meta.env.VITE_HOSTED_APP_URL?.trim() || DEFAULT_HOSTED_APP_URL;
16​
17function configuredBackendUrl(): string {
18 return import.meta.env.VITE_HTTP_URL?.trim() || import.meta.env.VITE_WS_URL?.trim() || "";
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;
25​
26function originFromUrl(value: string): string | null {
27 try {
28 return new URL(value).origin;
29 } catch {
30 return null;
31 }
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, or a window without a location (tests, static render), means
44 // no origin to be hosted at.
45 if (url === undefined && (typeof window === "undefined" || window.location === undefined)) {
46 return false;
47 }
48​
49 const hostedOrigin = originFromUrl(configuredHostedAppUrl());
50 return hostedOrigin !== null && (url ?? new URL(window.location.href)).origin === hostedOrigin;
52​
53export function readHostedPairingRequest(url: URL = new URL(window.location.href)) {
54 const host = url.searchParams.get("host")?.trim() ?? "";
55 const token = getPairingTokenFromUrl(url)?.trim() ?? "";
56 const label = url.searchParams.get("label")?.trim() ?? "";
57​
58 if (!host || !token) {
59 return null;
60 }
61​
62 return {
63 host,
64 token,
65 label,
66 } satisfies HostedPairingRequest;
68​
69export function hasHostedPairingRequest(url: URL = new URL(window.location.href)): boolean {
70 return readHostedPairingRequest(url) !== null;
72​
73export function buildHostedPairingUrl(input: {
74 readonly host: string;
75 readonly token: string;
76 readonly label?: string | null;
77}): string {
78 const url = new URL("/pair", configuredHostedAppUrl());
79 url.searchParams.set("host", input.host);
80​
81 const label = input.label?.trim();
82 if (label) {
83 url.searchParams.set("label", label);
84 }
85​
86 return setPairingTokenOnUrl(url, input.token).toString();
88​
89export function buildHostedChannelSelectionUrl(input: {
90 readonly channel: HostedAppChannel;
91}): string {
92 const url = new URL("/__t3code/channel", configuredHostedAppUrl());
93 url.searchParams.set("channel", input.channel);
94 return url.toString();